0

我的代码:

var lastName = employees
   .Where(a => a.Number ==
      (dm.MTM.Where(b => b.MTT.IsManager)
             .Select(c => c.Number)
             .FirstOrDefault()))
   .Select(z => z.LastName)
   .FirstOrDefault();

错误信息:

Unable to create a constant value of type 'XXX.Models.Mt.MTM'. Only primitive types or enumeration types are supported in this context. 
4

2 回答 2

1

尝试:

int? num = dm.MTM.Where(b => b.MTT.IsManager).Select(c => c.Number).FirstOrDefault();
var lastName = employees.Where(a => a.Number == num).Select(z => z.LastName).FirstOrDefault();

但是你应该加一张支票

if (num == null)
{
    // bad things, don't execute second query
}

两条指令之间。

错误是因为在实体框架查询中你不能做太多花哨的“事情”,比如计算所需的事情num

于 2013-08-16T10:29:50.777 回答
0

尝试:

// Calculate the number outside of the main query
// because the result is fixed
var nb = dm.MTM
      .Where(b => b.MTT.IsManager)
      .Select(c => c.Number)
      .FirstOrDefault();

// Perform the main query with the number parameter already calculated before
string lastName = String.Empty;
if (nb != null) // if null no need to run the query
{  
   lastName = employees
      .Where(a => a.Number == nb)
      .Select(z => z.LastName)
      .FirstOrDefault();
}

您不需要从数据库中获取每个员工的数字,在运行主查询之前计算值。这将更快,更不容易出错并且更适合缓存。

于 2013-08-16T10:35:32.277 回答