我无法调用EF中的实体

huangapple go评论77阅读模式
英文:

I can not call the entity in EF

问题

当我尝试调用 CategoryTopCategory 时,我无法调用 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&lt;Category&gt;

@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 = &quot;Varchar&quot;)]
    [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 =&gt; 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.

huangapple
  • 本文由 发表于 2023年5月11日 00:15:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定