我在L2S类dbml中有5个表:全局>>类别>> 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在一个查询中获取“全局”记录,获取任何主键值,并使用一个查询来获取“category”子级。取得这些结果,并将其放入与全局链接的集合中。然后使用所有类别关键字并执行一个查询以获取itemtype子项并将其链接到其关联的集合中。 (从(类别中的CategoryType中选择*(从(#,#,#)中的GlobalID中选择类别ID)选择)的顺序

我想知道如何以最少的查询来适本地渴望加载关联的子级,以及可能如何一般地完成我的例程,而不知道我需要多远的时间来构建层次结构,而是给定父实体,获取所有关联的子级集合,然后执行我需要做什么。

最佳答案

Linq to SQL在急切加载方面有一些限制。



有关详细信息,请参见:

http://www.cnblogs.com/cw_volcano/archive/2012/07/31/2616729.html

关于c# - 使用Linq to SQL,我如何急于加​​载所有子级和任何嵌套的子级结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1191331/

10-11 02:19