Entity Framework 4.1 Retrieving self referencing data

試著忘記壹切 提交于 2019-12-03 14:23:57

If you need to access child categories you can add a collection property to your model

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; }
}

Then you can setup the model as

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

Edit

You should check whether ParentCategory is null or not.

@if(Model.ParentCategory != null){
  <div>@Model.ParentCategory.Name</div>
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!