我首先使用 Entity Framework 4.1 代码和 ASP.NET MVC 3,并且我正在努力正确设置自引用。我有一个类别类。它必须是自我引用的。当表中ParentCategoryId为空时,类别可以是父类别。如果某个类别具有带值的 ParentCategoryId,则表示它属于父类别。
我跟着这个article http://www.codeproject.com/Articles/206410/How-to-Configure-a-Self-Referencing-Entity-in-Code关于代码项目。
这是我的类别:
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 查询类别时,它必须带回父类别(仅在需要时加载)。它还必须加载任何子类别(仅在需要时)。我尚未将列表添加到子类别的类别类中。
检索具有父类别和子类别的类别时,上述查询会是什么样子?
EDIT
这是我检索类别的方法:
public Category GetById(int id)
{
return db
.Categories
.Find(id);
}
由于 ParentCategory 引用可以为空,我将如何在视图中显示它?我有以下内容:
@Model.ParentCategory.Name
..但是如果该类别没有与其关联的父类别,它不会给出错误吗?我将如何在视图中显示它?