ef6 code first 自关联表(树结构) 子集合始终为空

szkicc 2014-11-04 12:29:22
表结构
public class Test
{
[Key]
public int Id { get; set; }
public int? Pid { get; set; }
public string Name { get; set; }

public virtual Test Father { get; set; }
public ICollection<Test> Childs { get; set; }
}

数据
id pid Name
1 NULL a
2 1 aa
3 2 aaa
.....
Fluent配置
modelBuilder.Entity<Test>()
.HasMany(e => e.Childs)
.WithOptional(e => e.Father)
.HasForeignKey(e => e.Pid);

运行后,Childs 始终为空 Father可以正常取值
请问是那里设置有问题
...全文
408 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
szkicc 2014-11-09
  • 打赏
  • 举报
回复
谢谢 宝_爸 我在 public ICollection<Test> Childs { get; set; } 这里漏写了 virtual 正确应为 public virtual ICollection<Test> Childs { get; set; } 这样不用Include 也可正确获取值
宝_爸 2014-11-04
  • 打赏
  • 举报
回复
学习了下Fluent,很有趣的技术。 我在一个测试工程里测试了你的代码,问题不大,query的时候要加上includes就可以了. 我的测试代码: Model:

    public class Test
    {
        [Key]
        public int Id { get; set; }
        public int? Pid { get; set; }
        public string Name { get; set; }

        public virtual Test Father { get; set; }
        public ICollection<Test> Childs { get; set; }
    }
Context:

    public class TestContext : DbContext
    {
        public DbSet<Test> Tests { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Test>().HasKey(t => t.Id);
            modelBuilder.Entity<Test>()
                        .HasMany(t => t.Childs)
                        .WithOptional(t => t.Father)
                        .HasForeignKey(t => t.Pid);
        }
    }
使用

        private void button1_Click(object sender, EventArgs e)
        {
            using (var context = new TestContext())
            {
                //Test parenet = new Test() { Father = null, Name = "aa" };
                //context.Tests.Add(parenet);

                //Test child = new Test() { Father = parenet, Name = "bbb" };
                //context.Tests.Add(child);

                //Test grandChild = new Test() { Father = child, Name = "ccccccc" };
                //context.Tests.Add(grandChild);

                //context.SaveChanges();


                foreach (var t in context.Tests.Include("Childs"))
                {
                    foreach (var child1 in t.Childs)
                    {
                        Console.WriteLine("{0}, {1}, {2}", child1.Id, child1.Pid, child1.Name);
                    }
                    Console.WriteLine("{0}, {1}, {2}", t.Id, t.Pid, t.Name);
                }
            }
注意,insert代码被注释掉了,它只需要被运行一次。 如果你需要我的测试工程,可以给我邮件。

110,502

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧