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

asp.net c# entity-framework entity-framework-core

Question

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:

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.

When I change OnModelCreating event as below:

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

Then children property returns 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. I create a sql query and get using FromSql()

1
0
2/20/2020 2:02:52 PM

Popular Answer

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.

2
2/20/2020 2:03:16 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow