简体   繁体   English

实体框架核心父子项在同一个模型中,子节点返回null

[英]Entity Framework Core Parent Child items in the same model, children node returns null

I have a parent and child property inside one domain model.我在一个域模型中有一个父子属性。

public class TestModel
{
    public int ParentID { get; set; }
    public int ID{ get; set; }
    public string Name{ get; set; }
    public virtual TestModel parent { get; set; }
    public virtual List<TestModel> children { get; set; }
}

When I write OnModelCreating event as below:当我编写OnModelCreating事件如下:

builder.Entity<TestModel>().HasOne(b => b.parent).WithMany(a => a.children).HasForeignKey(b => b.ID);

In debug mode children node returns hierarchical same and I get 'Self referencing loop detected for property 'parent' with type TestModel' error on JsonConvert.SerializeObject.在调试模式下,子节点返回分层相同,并且我在 JsonConvert.SerializeObject 上收到“检测到属性 'parent' 类型为 TestModel' 错误的自引用循环。

When I change OnModelCreating event as below:当我改变OnModelCreating事件如下:

builder.Entity<TestModel>().HasOne(b => b.parent).WithMany(a => a.children).HasForeignKey(b => b.ParentID);

Then children property returns null.然后 children 属性返回 null。 How can I solve this problem?我怎么解决这个问题? How can I load children property correctly?如何正确加载子属性?

I hope somebody can help me.我希望有人可以帮助我。

PS: TestModel not in any context so I cant Include. PS:TestModel 不在任何上下文中,所以我不能包含。 I create a sql query and get using FromSql()我创建了一个 sql 查询并使用 FromSql()

The second is the right one, but I suspect that when loading, you are not eagerly fetching the children.第二个是正确的,但我怀疑在加载时,您并没有急切地去取孩子。 Try this:尝试这个:

var one = context.Set<TestModel>().Include(x => x.children).FirstOrDefault();

Another option is to use lazy loading.另一种选择是使用延迟加载。 See more here: https://docs.microsoft.com/en-us/ef/core/querying/related-data .在此处查看更多信息: https : //docs.microsoft.com/en-us/ef/core/querying/related-data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM