【问题标题】:Parent/Child with EF6 child collection always null具有 EF6 子集合的父/子始终为空
【发布时间】:2019-03-29 14:05:02
【问题描述】:

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

数据库

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

【问题讨论】:

  • 是否启用延迟加载?
  • 顺便说一句,我建议使用 C# 的 nameof 运算符而不是对字符串 "ParentMyListId" 进行硬编码,因此您可以使用 [ForeignKey( nameof( MyList.ParentMyListId ) )] - 以获得额外的构建时安全性。

标签: c# sql entity-framework ef-fluent-api


【解决方案1】:

我在 EF 6.1.3 版本中尝试了相同的结构,它的工作原理很迷人。我添加了输出图像和数据库中存在的数据。如果您在配置中禁用加载,唯一可能会停止工作。我希望它对你有用,请尝试我的示例代码。

  // 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();
    }

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

【讨论】:

  • 我想我将不得不做更多的故障排除。不知道为什么我的不起作用。
  • 请分享你的 dbcontext 类
  • 我可以看到你 idsabled 延迟加载然后你如何获得导航属性。如果你愿意的话。使用这样的东西。 ctx.Lists.Include("MyListChildren").ToList();
  • 在 ToList() 之前试试这个 Include("MyListChildren") 希望对你有帮助
  • @user3953989 在 ToList() 之前试试这个 Include("MyListChildren") 希望对你有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多