【发布时间】:2009-07-28 00:20:39
【问题描述】:
我在 L2S 类 dbml 中有 5 个表:Global >> Categories >> ItemType >> Item >> ItemData。对于下面的示例,我只介绍了 itemtype。
//cdc is my datacontext
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Global>(p => p.Category);
options.AssociateWith<Global>(p => p.Category.OrderBy(o => o.SortOrder));
options.LoadWith<Category>(p => p.ItemTypes);
options.AssociateWith<Category>(p => p.ItemTypes.OrderBy(o => o.SortOrder));
cdc.LoadOptions = options;
TraceTextWriter traceWriter = new TraceTextWriter();
cdc.Log = traceWriter;
var query =
from g in cdc.Global
where g.active == true && g.globalid == 41
select g;
var globalList = query.ToList();
// In this case I have hardcoded an id while I figure this out
// but intend on trying to figure out a way to include something like globalid in (#,#,#)
foreach (var g in globalList)
{
// I only have one result set, but if I had multiple globals this would run however many times and execute multiple queries like it does farther down in the hierarchy
List<Category> categoryList = g.category.ToList<Category>();
// Doing some processing that sticks parent record into a hierarchical collection
var categories = (from comp in categoryList
where comp.Type == i
select comp).ToList<Category>();
foreach (var c in categories)
{
// Doing some processing that stick child records into a hierarchical collection
// Here is where multiple queries are run for each type collection in the category
// I want to somehow run this above the loop once where I can get all the Items for the categories
// And just do a filter
List<ItemType> typeList = c.ItemTypes.ToList<ItemType>();
var itemTypes = (from cat in TypeList
where cat.itemLevel == 2
select cat).ToList<ItemType>();
foreach (var t in itemTypes)
{
// Doing some processing that stick child records into a hierarchical collection
}
}
}
"列表类型列表 = c.ItemTypes.ToList();"
这条线在 foreach 中执行了无数次,并执行了一个查询来获取结果,我在一定程度上理解了原因,但我认为它会渴望加载 Loadwith 作为一个选项,就像用一个查询获取所有内容一样。
所以基本上我希望 L2S 在幕后在一个查询中获取“全局”记录,获取任何主键值,使用一个查询获取“类别”子项。获取这些结果并将它们粘贴到与全球相关的集合中。然后获取所有类别键并执行一个查询以获取 itemtype 子项并将它们链接到它们的关联集合中。 (Select * from ItemTypes Where CategoryID in (select categoryID from Categories where GlobalID in (#,#,#)) 顺序的东西
我想知道如何用最少的查询正确地预先加载关联的子项,以及如何完成我的例程,一般不知道我需要构建层次结构的深度,但是给定一个父实体,获取所有关联的子集合然后做我需要做的。
【问题讨论】:
标签: c# asp.net linq-to-sql