给定以下代码:
var EmployeeXPosition = from emp in context.WTDEmployee
from ep in emp.WTDEmployeeXOXPosition
select new {
EmployeeId = emp.id,
FullNameAndPosition = string.Format("{0} {1} : {2}", emp.FirstName, emp.LastName, ep.WTDPosition.Position)
};
它给出了错误:
LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object, System.Object, System.Object)' method, and this method cannot be translated into a store expression.
果然我能做到:
emp.FirstName+" "+ emp.LastName +" : " + ep.WTDPosition.Position
但它看起来很难看,关于如何使用 string.Format
有什么建议吗?
最佳答案
我通常通过创建两个语句来解决这个问题 - 一个在 LinqToEntities(或 ToSql,或其他)中,另一个在 LinqToObjects 中。我在商店里做我需要做的事情,然后对内存中的对象做一个单独的处理步骤。这融合了两全其美。
var EmployeeXPosition = from emp in context.WTDEmployee
from ep in emp.WTDEmployeeXOXPosition
select new {
emp.id,
emp.FirstName,
emp.LastName,
ep.WTDPosition.Position
};
var result = from item in EmployeeXPosition.ToList()
select new
{
EmployeeId = item.id,
FullNameAndPosition = string.Format("{0} {1} : {2}", item.FirstName, item.LastName, item.Position)
};
关于c# - 在 Linq 投影中使用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3765262/