英文:
I can not call the entity in EF
问题
当我尝试调用 Category 的 TopCategory 时,我无法调用 TopCategory 的其他属性。它返回 System.NullReferenceException。我尝试在模型中使用 virtual 但不起作用。
@using WTvP_E_Ticaret_Projesi.Models.Classes
@model List<Category>
@foreach (var category in Model)
{
...(其他内容)
@category.TopCategory.CategoryName
...(其他内容)
}
categoryController.cs
Context context = new Context();
public ActionResult Index()
{
context.Configuration.ProxyCreationEnabled = false;
var categories = context.Categories.ToList();
return View(categories);
}
我的模型 Category.cs
public class Category
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CategoryID { get; set; }
[Column(TypeName = "Varchar")]
[StringLength(25)]
public string CategoryName { get; set; }
public Category TopCategory { get; set; }
}
英文:
When I'm trying to call TopCategory of Category, I can't call other properties of TopCategory. It returns System.NullReferenceException. I tried it using it with virtual in Model but it didn't work.
@using WTvP_E_Ticaret_Projesi.Models.Classes
@model List<Category>
@foreach (var category in Model)
{
... (other stuffs)
@category.TopCategory.CategoryName
... (other stuffs)
}
categoryController.cs
Context context = new Context();
public ActionResult Index()
{
context.Configuration.ProxyCreationEnabled = false;
var categories = context.Categories.ToList();
return View(categories);
}
My model Category.cs
public class Category
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CategoryID { get; set; }
[Column(TypeName = "Varchar")]
[StringLength(25)]
public string CategoryName { get; set; }
public Category TopCategory { get; set; }
}
答案1
得分: 0
使用 Include()
加载相关实体:
var categories = context.Categories.Include(c => c.TopCategory).ToList();
有关详细描述,请参阅:Eagerly Loading
> 渴望加载是一种查询一种实体类型并作为查询的一部分加载相关实体的过程。通过使用 Include
方法实现渴望加载。
英文:
Load related entities by using the Include()
:
var categories = context.Categories.Include(c => c.TopCategory).ToList();
For detailed description see: Eagerly Loading
> Eager loading is the process whereby a query for one type of entity
> also loads related entities as part of the query. Eager loading is
> achieved by use of the Include
method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论