具有EF6子集合的父/子总是为空

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了具有EF6子集合的父/子总是为空相关的知识,希望对你有一定的参考价值。

当我通过EF拉取MyList对象时,父关系正确关联,但Children集合始终为null。不知道我做错了什么,几乎每篇文章都表明这样做。

数据库

CREATE TABLE [dbo].[MyList] (
    [MyListId]     BIGINT           IDENTITY (1, 1) NOT NULL,
    [ParentMyListId] BIGINT NULL, 
    CONSTRAINT [PK_MyList] PRIMARY KEY CLUSTERED ([MyListId] ASC) WITH (FILLFACTOR = 90),
    CONSTRAINT [FK_MyList_MyList_MyListId] FOREIGN KEY (ParentMyListId) REFERENCES MyList(MyListId)
);

模型

public class MyList
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long MyListId { get; set; }
    public long? ParentMyListId { get; set; }

    [ForeignKey("ParentMyListId")]
    public virtual List MyListParent { get; set; }

    public virtual ICollection<MyList> MyListChildren { get; set; }
}

的DbContext

public class MyContext : DbContext
{
    public MyContext() : base(Properties.Settings.Default.DbContext)
    {
        Configuration.LazyLoadingEnabled = false;
    }

    public DbSet<MyList> MyLists { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyList>()
        .ToTable("MyList", "dbo")
        .HasOptional(x => x.MyListParent)
        .WithMany(x => x.MyListChildren)
        .HasForeignKey(x => x.ParentMyListId)
        .WillCascadeOnDelete(false);
    }

    base.OnModelCreating(modelBuilder);
}
答案

我尝试在EF 6.1.3版本中使用相同的结构,它就像魅力一样。我添加了db中输出和数据的图像。如果在配置中禁用加载,则唯一可能停止工作的事情。我希望它适合你,请尝试我的示例代码。

  // Your entity class I added name property to show you the results 
   public class MyList
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long MyListId { get; set; }
        public long? ParentMyListId { get; set; }

        public string Name { get; set; }

        [ForeignKey("ParentMyListId")]
        public virtual MyList MyListParent { get; set; }

        public virtual ICollection<MyList> MyListChildren { get; set; }
    }       

     // DBContext please note no configuration properties set just default constructor 
     // you need t check here if you have set soemthing here 
       public class TestContext : DbContext
        {
            public TestContext()
                : base("name=TestConnection")
            {
            }               

            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Entity<MyList>()
                .ToTable("MyList", "dbo")
                .HasOptional(x => x.MyListParent)
                .WithMany(x => x.MyListChildren)
                .HasForeignKey(x => x.ParentMyListId)
                .WillCascadeOnDelete(false);

            }

            public virtual DbSet<MyList> Lists { get; set; }
        }

控制台应用程序显示结果:

    static void Main(string[] args)
    {
        using (var ctx = new TestContext())
        {

            // for testing to see al working 
            //this is important to read the entity first .
            var parent = ctx.Lists.ToList();

            foreach (var p in parent)
            {
                foreach (var child in p.MyListChildren)
                {
                    Console.WriteLine(string.Format(@"Parent Name {0}  has child with name {1}", p.Name, child.Name));
                }
            }

        }

        Console.ReadLine();
    }

在数据库中输出应用程序和数据......

enter image description here

以上是关于具有EF6子集合的父/子总是为空的主要内容,如果未能解决你的问题,请参考以下文章

使用 nHibernate 选择具有许多子集合的实体的性能不佳

具有子集合的实体在 WCF 中导致问题:如果您使用 DataContractSerializer,请考虑使用 DataContractResolver

Cloud Firestore 如何查找包含特定文档 ID 的子集合的所有文档?

在 Firestore 中删除包含所有子集合和嵌套子集合的文档

子集合的 Firestore 监听器

NHibernate:如何获取没有子集合的对象?