简体   繁体   中英

Entity Framework - Load related entity on related entites (one to many to one)

I'm trying to load an object (a) and that object has a collection of objects (b), each object:b has single objects attached to them. I've cut down the code below to show you how it's setup.

I can without any problems load 'MyImprovement'. I can in that same moment load the collection of 'MyCondition'. But what I fail to load is 'MyComponent' that is referenced in the 'MyCondition'...

I managed to find some samples using .Include and .ThenInclude, however, .ThenInclude does not exist from what I can see?

I've tried every possible aspect of this and I still think that it should be possible to do,... right?

Anyone who's up for the task? I'm completely lost right now, so please help! Thanks in advance!

/Karl

public class MyImprovement
{
    [Key]
    public int MyImprovementId { get; set; }
    public virtual ICollection<MyCondition> Conditions { get; set; }
}

public class MyCondition
{
    [Key]
    public int MyConditionId { get; set; }
    public int? ComponentId { get; set; }
    public virtual MyComponent ConditionalMyComponent { get; set; }
}

public class MyComponent
{
    [Key]
    public int ComponentId { get; set; }
    public string PDNumber { get; set; }
}     

// Code to load the first 2 levels of objects
MyImprovement improvement = dbx.MyImprovements
                                  .Include("Conditions")
                                  .Where(x => x.ImprovementId == id)
                                        .First();

If you want to eager-load complex entity graph, you can combine multiple .Include()- Methods with following style:

MyImprovement improvement = dbx.MyImprovements
                                  .Include("Conditions")
                                  .Include("Conditions.ConditionalMyComponent")
                                  .Where(x => x.ImprovementId == id)
                                        .First();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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