如何构造LINQ to Entities查询以直接加载子对象,而不是调用Reference属性或Load()

JC *_*bbs 43 c# linq linq-to-entities

我是新手使用LINQ to Entities(或实体框架,无论他们调用它),我写了很多这样的代码:

var item = (from InventoryItem item in db.Inventory
            where item.ID == id
            select item).First<InventoryItem>();
Run Code Online (Sandbox Code Playgroud)

然后像这样调用该对象上的方法:

var type = item.ItemTypeReference;
Run Code Online (Sandbox Code Playgroud)

要么

var orders = item.OrderLineItems.Load();
Run Code Online (Sandbox Code Playgroud)

检索子对象或相关对象.

我没有对数据库进行分析或挖得太深,但我的猜测是,当我调用.Load()或*Reference属性时,我实际上正在再次调用数据库.如果是这种情况,有没有办法在我的初始LINQ表达式中获取这些对象?

Rob*_*ner 62

您希望在此"整形查询结果"文章中使用.Include(字符串)方法引用.

var item = from InventoryItem item in
              db.Inventory.Include("ItemTypeReference").Include("OrderLineItems")
           where item.ID == id
           select item;
Run Code Online (Sandbox Code Playgroud)

包含也可能是"sql"样式语法.

另请参阅该文章有关从LINQ到SQL移动到LINQ到实体.

对于其他寻找Linq to SQL问题解决方案的人,您希望执行以下操作(替换DataContext和其他类型的任何内容):

using (DataContext db = new DataContext())
{
    DataLoadOptions options = new DataLoadOptions();
    options.LoadWith<InventoryItem>(ii => ii.ItemTypeReference);
    options.LoadWith<InventoryItem>(ii => ii.OrderLineItems);
    db.LoadOptions = options;

    var item = from InventoryItem item in db.Inventory
               where item.ID == id
               select item;
}
Run Code Online (Sandbox Code Playgroud)

对于该特定上下文,每当加载父项(InventoryItem)时,这将加载LoadWith中指定的属性.

在回答James和Jesper的其他一些问题时,请查看这个问题