在构建LINQ时获取代码中的错误

时间:2013-08-16 10:28:24

标签: linq entity-framework c#-4.0 asp.net-mvc-4

我的代码:

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. 

2 个答案:

答案 0 :(得分: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所需的事情。

答案 1 :(得分: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();
}

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