简体   繁体   English

EF:加载相关对象的相关对象

[英]EF: Loading related objects of related objects

I can´t find a way to load an object from a DB with all its related objects. 我找不到从DB加载对象及其所有相关对象的方法。 Concerning this simplified model (ID-Properties not shown): 关于这个简化的模型(ID-Properties未显示):

class MainClass 
{  
    public virtual ICollection<FirstLevelClass> FirstLevelObjects {get; set;}  
}

class FirstLevelClass
{  
    public virtual ICollection<SecondLevelClassA> SecondLevelObjectsA {get; set;}
    public virtual ICollection<SecondLevelClassB> SecondLevelObjectsB {get; set;}
}

class SecondLevelClassA
{
    public virtual int SomeValue {get; set;}

}
class SecondLevelClassB
{
    public virtual int SomeValue {get; set;}

}

The DbContext is on "MainClass"-Objects: DbContext在“MainClass”上 - 对象:

public SampleContext : DbContext
{
    public DbSet<MainClass> MainClassObjects {get; set;}
}

How can I load an MainClass-object from db with all first- and second-level-objects? 如何从db加载包含所有第一级和第二级对象的MainClass对象? I can do: 我可以:

using (var context = new SampleContext())
{
    var MainClassObjects = context.MainClassObjects.Include(p => p.FirstLevelObjects).ToList();

    // ...move objects from the context to program logic...

}

but how do I get SecondLevelObjects? 但是我如何获得SecondLevelObjects? I´m missing something like: 我错过了类似的东西:

using (var context = new SampleContext())
{
    var MainClassObjects = context.MainClassObjects.Include(p => p.FirstLevelObjects.SecondLevelObjects).ToList();

    // ...move objects from the context to program logic...

}

Is this even possible or do I have to adapt the DbSets in the DbContext? 这甚至是可能的还是我必须在DbContext中调整DbSets?

One solution can be to use Include method's other overload which takes a string like this: 一种解决方案可以是使用Include方法的其他重载,它采用如下字符串:

var MainClassObjects = context.MainClassObjects
.Include("FirstLevelObjects")
.Include("FirstLevelObjects.SecondLevelObjects")
.ToList();

Update: 更新:

When you're using this method you just need to determine the paths you want to fetch so for updated question you can use this: 当您使用此方法时,您只需确定要获取的路径,以便更新问题,您可以使用此方法:

var MainClassObjects = context.MainClassObjects
.Include("FirstLevelObjects.SecondLevelObjectsA")
.Include("FirstLevelObjects.SecondLevelObjectsB")
.ToList();

Try this: 尝试这个:

using (var context = new SampleContext())
{
    var MainClassObjects = context.MainClassObjects.Include(p => p.FirstLevelObjects.SelectMany(s => s.SecondLevelObjects)).ToList();

// ...move objects from the context to program logic...

}

You should add a .Select() statement to get an object or a list. 您应该添加.Select()语句来获取对象或列表。

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

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