同一类的映射子项与实体框架代码优先 [英] Mapping child items of same class with Entity Framework Code First

查看:101
本文介绍了同一类的映射子项与实体框架代码优先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用映射代码EF首先

I'm trying to map a fairly "standard" category model using EF Code First

public class Category
{
    public int ID { get; set; }
    public int ParentID { get; set; }

    public string Name { get; set; }

    public Category ParentCategory { get; set; }
    public List<Category> ChildCategories { get; set; }
}



我沿着线得到的东西:

I've got something along the lines of:

modelBuilder.Entity<Category>()
    .HasOptional(t => t.ParentCategory)
    .WithMany()
    .HasForeignKey(t => t.ParentCategoryID)
    .WillCascadeOnDelete();



但是,这似乎并没有采取ChildCategories照顾??

But this doesn't seem to take care of ChildCategories??

我缺少的东西。

要避免重复问题的说法,我也跟着以下,但并没有完全回答我的具体查询:

To avoid the duplicate question argument, I followed the following, however didn't quite answer my specific query:

代码首先映射实体框架层次

实体框架CTP5代码优先映射 - 同一表的外键

推荐答案

你的实体改为

public class Category
{
    public int ID { get; set; }
    public int? ParentID { get; set; }

    public string Name { get; set; }

    public virtual Category ParentCategory { get; set; }
    public virtual IList<Category> ChildCategories { get; set; }
}

PARENTID 可空,并让 ChildCategories 偷懒装,使其虚拟化。

Make ParentID nullable and to allow ChildCategories to be lazy loaded, make it virtual.

这篇关于同一类的映射子项与实体框架代码优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆