gpt4 book ai didi

entity-framework - Entity Framework 4.1 检索自引用数据

转载 作者:行者123 更新时间:2023-12-04 07:23:22 26 4
gpt4 key购买 nike

我首先使用 Entity Framework 4.1 代码和 ASP.NET MVC 3,我正在努力正确设置我的自引用。我有一个类别类。它必须是对自身的自引用。当表中的 ParentCategoryId 为空时,类别可以是父类别。如果一个类别有一个带有值的 ParentCategoryId,那么这意味着它属于一个父类别。

我关注了这个 article在代码项目上。

这是我的类别类:

public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public bool IsActive { get; set; }
public virtual Category ParentCategory { get; set; }
public int? ParentCategoryId { get; set; }
}

我的上下文类:
public class PbeContext : DbContext
{
public DbSet<Category> Categories { get; set; }

protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
dbModelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

dbModelBuilder.Entity<Category>()
.HasOptional(c => c.ParentCategory)
.WithMany()
.HasForeignKey(p => p.ParentCategoryId);
}
}

不知道以上是否正确?

有人可以帮我解决这个问题吗?我需要的是,当我通过 id 查询类别时,它必须带回父类别(仅在需要时加载)。此外,它必须加载任何子类别(仅在需要时)。我还没有为子类别的类别类添加列表。

上面的查询如何检索带有父类别和子类别的类别?

编辑

这是我检索类别的方式:
public Category GetById(int id)
{
return db
.Categories
.Find(id);
}

因为 ParentCategory 引用可以为空,我将如何在 View 中显示它?我有以下几点:
@Model.ParentCategory.Name

..但是如果该类别没有与之关联的父类别,它会不会出错?我将如何在 View 中显示它?

最佳答案

如果您需要访问子类别,您可以向模型添加集合属性

public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public bool IsActive { get; set; }
public virtual Category ParentCategory { get; set; }
public int? ParentCategoryId { get; set; }
public virtual ICollection<Category> ChildCategories{ get; set; }
}

然后您可以将模型设置为
      dbModelBuilder.Entity<Category>()
.HasOptional(c => c.ParentCategory)
.WithMany(c => ChildCategories)
.HasForeignKey(p => p.ParentCategoryId);

编辑

您应该检查是否 ParentCategory是否为空。
@if(Model.ParentCategory != null){
<div>@Model.ParentCategory.Name</div>
}

关于entity-framework - Entity Framework 4.1 检索自引用数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6690849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com