我是使用 LINQ to Entities(或实体框架,无论他们如何称呼它)的新手,我正在编写很多这样的代码:
var item = (from InventoryItem item in db.Inventory
where item.ID == id
select item).First<InventoryItem>();
然后像这样调用该对象的方法:
var type = item.ItemTypeReference;
or
var orders = item.OrderLineItems.Load();
检索子对象或相关对象。
我还没有对数据库进行概要分析或深入挖掘,但我的猜测是,当我调用 .Load() 或 *Reference 属性时,我实际上是在对数据库进行另一次调用。如果是这种情况,有什么方法可以在我的初始 LINQ 表达式中获取这些对象吗?
您想在此使用 .Include(string) 方法引用“塑造查询结果” http://msdn.microsoft.com/en-us/library/bb896272.aspx文章。
var item = from InventoryItem item in
db.Inventory.Include("ItemTypeReference").Include("OrderLineItems")
where item.ID == id
select item;
包含也可能有一个“sql”样式语法。
另请参阅此article http://blogs.msdn.com/adonet/archive/2008/10/07/migrating-from-linq-to-sql-to-entity-framework-eager-loading.aspx关于从 LINQ-to-SQL 迁移到 LINQ-to-Entities。
对于其他正在寻找此问题解决方案的人Linq 到 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;
}
每当加载特定上下文的父项 (InventoryItem) 时,这都会加载 LoadWith 中指定的属性。
为了回答 James 和 Jesper 的一些进一步问题,请查看此question https://stackoverflow.com/questions/648782/how-do-i-create-a-where-condition-on-a-sub-table-in-linq
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)