LINQ to 实体无法识别方法 'Int32 Min(Int32, Int32)'?



我在执行以下代码时遇到了这个错误,有什么想法吗?


LINQ to Entities does not recognize the method 'Int32 Min(Int32, Int32)' method, and this method cannot be translated into a store expression.

result = items.ToList()
                    .Select(b => new BatchToWorkOnModel()
                    {
                        BatchID = b.Batch.ID,
                        SummaryNotes = b.Batch.Notes,
                        RowVersion = b.Batch.RowVersion,
                        Items = items
                            .Select(i => new ItemToWorkOnModel()
                            {
                                SupplierTitle = i.Title,
                                ItemID = i.ID,
                                BatchID = i.BatchID ?? 0,
                                ItemDate = i.PubDate,
                                // KB - Issue 276 - Return the correct Outlet name for each item
                                Outlet = i.Items_SupplierFields != null ? i.Items_SupplierFields.SupplierMediaChannel != null ? i.Items_SupplierFields.SupplierMediaChannel.Name : null : null,
                                Status = ((short)ItemStatus.Complete == i.StatusID ? "Done" : "Not done"),
                                NumberInBatch = i.NumInBatch,
                                Text = string.IsNullOrEmpty(i.Body) ? "" : i.Body.Substring(0, Math.Min(i.Body.Length, 50)) + (i.Body.Length < 50 ? "" : "..."),
                                IsRelevant = i.IsRelevant == 1,
                                PreviouslyCompleted = i.PreviouslyCompleted > 0 ? true : false
                            }).ToList()
                    })
                    .FirstOrDefault();

EF查询提供程序似乎没有实现Math.Min。您应该能够通过简单地在项目集合上应用AsEnumerable来修复它,从而使用Linq-to-Objects来执行表达式;

Items = items.AsEnumerable().Select(i => new ItemToWorkOnModel()...

如果将where条件添加到项目选择中(将整个表中的所有项目都包含在内似乎有点奇怪),则需要将其添加到AsEnumerable()之前,以允许EF在数据库中进行筛选。

此外,您只需要查询的第一个结果,但在将列表缩减为单个项目之前,您将使用ToList()获取所有结果。您可能需要删除ToList(),以便EF/底层数据库只能返回单个结果;

result = items.Select(b => new BatchToWorkOnModel()...

您不需要Math.Min

有问题的线路是:

Text = string.IsNullOrEmpty(i.Body)
       ? "" : i.Body.Substring(0, Math.Min(i.Body.Length, 50)) + (i.Body.Length < 50 ? "" : "...")

那么这行返回的是什么呢?

如果i.Body为null或为空,则返回一个空字符串。如果长度为50个或更多字符,则返回一个50个字符的子字符串并附加"…"。
如果长度小于50,它会取一个与字符串长度相同的子字符串,并附加一个空字符串。但这只是最初的字符串。

Text = string.IsNullOrEmpty(i.Body)
       ? "" : (i.Body.Length < 50 ? i.Body : i.Body.Substring(0, 50) + "...")

最新更新