在LINQ GroupBy中缺少外键对象? [英] Foreign Key Object Missing in LINQ GroupBy?

查看:203
本文介绍了在LINQ GroupBy中缺少外键对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 LINQ 查询中使用 GroupBy 。我的查询工作正常,除了我的外键对象丢失。然后,我试着在查询中添加 Include 。以下是我的代码:

  public ActionResult GetEmployees()
{
var Emloyees = db.Employees。 AsQueryable已();
Emloyees.GroupBy(e => new {e.JobTitleId,e.GenderId})
.Select(tr => new MyObject
SalaryTotal = tr.Sum(r =>包含(tr => tr.JobTitle).Include(tr => tr.Gender).ToList();
}

我得到这个异常:


查询的结果类型既不是实体类型也不是具有实体元素类型的集合类型。包含路径只能针对具有这些结果类型之一的查询指定。


我试图在<$ c $之前添加它c> GroupBy 并直接在 db.Employees.AsQueryable()中,但没有任何工作。我做错了什么?

解决方案

问题在于你正在使用.Select(...)进行投影,之后您的包含无法解析。该查询的结果将是一个MyObject列表,它不适用于包含实际在Employee上的包含。



所以请试试这样:

  Emloyees 
.GroupBy(e => new {e.JobTitleId,e.GenderId})
.Select(tr = > new MyObject {
SalaryTotal = tr.Sum(r => r.Salary),
JobTitle = tr.FirstOrDefault()。JobTitle,
Gender = tr.FirstOrDefault()。 Gender
})。ToList();

您将不得不使用2个附加属性来扩展MyObject,但查询的结果将成为您想要(我假设)。

I am using GroupBy in my LINQ queries. My query is working fine, except my foreign key objects are missing. Then, I tried to add Include in my query. Following is my code:

public ActionResult GetEmployees()
{
     var Emloyees = db.Employees.AsQueryable();
     Emloyees.GroupBy(e=> new {e.JobTitleId, e.GenderId})
             .Select(tr => new MyObject
                 SalaryTotal = tr.Sum(r=>r.Salary)
              }).Include(tr=>tr.JobTitle).Include(tr=>tr.Gender).ToList();
}

I am getting this exception:

The result type of the query is neither an EntityType nor a CollectionType with an entity element type. An Include path can only be specified for a query with one of these result types.

I tried to add it before GroupBy and directly in db.Employees.AsQueryable(), but nothing worked. What am I doing wrong?

解决方案

The problem is that you are doing a projection with the .Select(...), after which your includes cannot be resolved. The result of that query will be a list MyObject, which does not work for includes that are actually on Employee.

So Try it like this:

Emloyees
    .GroupBy(e=> new {e.JobTitleId, e.GenderId})
    .Select(tr => new MyObject {
        SalaryTotal = tr.Sum(r=>r.Salary),
        JobTitle = tr.FirstOrDefault().JobTitle,
        Gender = tr.FirstOrDefault().Gender
    }).ToList();

You will have to extend MyObject with 2 additional properties, but the result of your query will be what you want (I assume).

这篇关于在LINQ GroupBy中缺少外键对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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