linq - Entity Framework LINQ实体不识别方法'System.String Format(System.String, System.Object, System.Object)'

  显示原文与译文双语对照的内容
73 3

我有一个LINQ查询:


private void GetReceivedInvoiceTasks(User user, List<Task> tasks)


{


 var areaIds = user.Areas.Select(x => x.AreaId).ToArray();



 var taskList = from i in _db.Invoices


 join a in _db.Areas on i.AreaId equals a.AreaId


 where i.Status == InvoiceStatuses.Received && areaIds.Contains(a.AreaId)


 select new Task {


 LinkText = string.Format(Invoice {0} has been received from {1}, i.InvoiceNumber, i.Organisation.Name),


 Link = Views.Edit


 };


}



但它有问题我正在尝试创建任务。 对于每个新任务,当我将链接文本设置为"打招呼"这样的常量字符串时,。 不过在上面我试图用发票的属性来构建属性 linktext 。

我得到一个错误:

基 {System.SystemException} = {"LINQ 到实体不识别方法'system 。字符串格式( system 。string 。system 。object 。system 。object ) )'方法,不能将这里方法转换为存储表达式。"}

谁知道为什么任何人都知道做这个工作的另一种方法?

时间: 原作者:

103 2

Entity Framework 正试图在SQL端执行你的投影,它的中没有 string.Format 等等。 使用 AsEnumerable() 将该零件的计算强制用于Linq对象。

我已经给了你一个基于前面答案的答案:我已经给你重新构造你的查询了:


int statusReceived = (int)InvoiceStatuses.Received;


var areaIds = user.Areas.Select(x=> x.AreaId).ToArray();



var taskList = (from i in _db.Invoices


 where i.Status == statusReceived && areaIds.Contains(i.AreaId)


 select i)


. AsEnumerable()


. Select( x => new Task()


 {


 LinkText = string.Format("Invoice {0} has been received from {1}", x.InvoiceNumber, x.Organisation.Name),


 Link = Views.Edit


 });



还可以看到,在查询( Organisation.Name ) 中使用相关实体,确保向查询中添加正确的Include,或者特别实现这些属性:


var taskList = (from i in _db.Invoices


 where i.Status == statusReceived && areaIds.Contains(i.AreaId)


 select new { i.InvoiceNumber, OrganisationName = i.Organisation.Name})


. AsEnumerable()


. Select( x => new Task()


 {


 LinkText = string.Format("Invoice {0} has been received from {1}", x.InvoiceNumber, x.OrganisationName),


 Link = Views.Edit


 });



原作者:
...