你如何建立一个LINQ到实体查询到加载子对象直接,而不是调用参考属性或load() [英] How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()

查看:98
本文介绍了你如何建立一个LINQ到实体查询到加载子对象直接,而不是调用参考属性或load()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来使用LINQ到实体(或实体框架不管他们叫它),我写了很多code像这样的:

I'm new to using LINQ to Entities (or Entity Framework whatever they're calling it) and I'm writing a lot of code like this:

var item = (from InventoryItem item in db.Inventory
            where item.ID == id
            select item).First<InventoryItem>();

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

and then calling methods on that object like this:

var type = item.ItemTypeReference;

var orders = item.OrderLineItems.Load();

要检索子或相关对象。

我没有异形DB或挖得太深,但我的猜测是,当我叫.Load()或实际上我拨打另一个电话到DB一个*引用属性。如果是这样的话,有没有什么办法让我的最初的LINQ前pression这些对象?

I haven't profiled the DB or dug too deeply but my guess is that when I call a .Load() or a *Reference property I'm actually making another call to the DB. If this is the case, is there any way to get those objects in my initial LINQ expression?

推荐答案

您想在这个的塑造查询结果文章。

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

有可能是一个SQL的风格语法包括为好。

There is probably a "sql" style syntax for the Includes as well.

另请参阅该<一个href=\"http://blogs.msdn.com/adonet/archive/2008/10/07/migrating-from-linq-to-sql-to-entity-framework-eager-loading.aspx\">article有关从LINQ到SQL搬到LINQ到实体。

Also see this article about moving from LINQ-to-SQL to LINQ-to-Entities.

对于其他人寻找一个解决这个问题的 LINQ到SQL 你想要做以下(不管是什么,你有替代的DataContext和其他类型):

For others looking for a solution to this problem for Linq to SQL you want to do the following (Substitute DataContext and other types for whatever you have):

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;
}

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

This will load the properties specified in LoadWith whenever the parent item (InventoryItem) is loaded, for that particular context.

在响应来自詹姆斯和加斯帕一些其他问题,看看这个<一个href=\"http://stackoverflow.com/questions/648782/how-do-i-create-a-where-condition-on-a-sub-table-in-linq\">question

In response to some further questions from James and Jesper, check out this question

这篇关于你如何建立一个LINQ到实体查询到加载子对象直接,而不是调用参考属性或load()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆