开发者

LINQ to Entities - "Including" a complex object while also grouping

开发者 https://www.devze.com 2022-12-13 05:31 出处:网络
I have a set of tasks that I need to select distinct on (group by in L2E).Those tasks have a referenced property, \"Activity\" that开发者_如何学Go I need to be loaded so that I can reference the task.

I have a set of tasks that I need to select distinct on (group by in L2E). Those tasks have a referenced property, "Activity" that开发者_如何学Go I need to be loaded so that I can reference the task.Activity object. In the first example below, this works fine. However, when I group by the description, the activity does not get loaded. What am I missing?

tasks = 
    (from x in Db.Task.Include("Activity") select x)
    .ToList();

tasks =
    (from x in Db.Task.Include("Activity")
     group x by x.Description
     into groupedByDescription
         select groupedByDescription.FirstOrDefault()).ToList();


groupedByDescription is not an entity; it's a group of entities. You can only Include when you select an entity.

More information is in this tip.

Hard to give a workaround without knowing what problem you are trying to solve.


I would like to expound the question because I think the question was not answered.

Based on example from here: IQueryable> prodQuery = from prod in db.Products group prod by prod.CategoryID into grouping select grouping;

foreach (IGrouping<Int32, Product> grp in prodQuery)
{
    Console.WriteLine("\nCategoryID Key = {0}:", grp.Key);
    foreach (Product listing in grp)
    {
        Console.WriteLine("\t{0}", listing.ProductName);
    }
}

If the table Product has a foreign key relation with table T_Category, the only way to access the category is via db.Product.T_Category.CategoryID. If this is the case, would an include work to be able to get the other information in T_Category such as T_Category.CategoryName?

IQueryable> prodQuery = from prod in db.Products.include("T_Category") group prod by prod.T_Category.CategoryID into grouping select grouping;

foreach (IGrouping<Int32, Product> grp in prodQuery)
{
    Console.WriteLine("\nCategoryID Key = {0}:", grp.Key);
    foreach (Product listing in grp)
    {
        Console.WriteLine("\t{0}", listing.ProductName);
        Console.WriteLine("\t{0}", listing.T_Category.CategoryID);
        Console.WriteLine("\t{0}", listing.T_Category.CategoryName);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消