String.Format 或 toString 在 linq 中不允许

String.Format or toString not allowed in linq

下面的代码不喜欢并抛出以下错误。

LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object)' method, and this method cannot be translated into a store expression.

在我将运输方式的费用从十进制更改之前,我能够做到这一点吗?到十进制。我把它改成了十进制,它开始抛出一个错误,然后我把它改回来,现在它仍然不喜欢这样。这里做错了什么。我只是想使文本成为运输方式名称与 - 的连接,并将成本作为文本。

  var ShippingMethods = db.ShippingMethods.Select(x => new SelectListItem()
                    {
                        Text = x.Name + " - " + String.Format("c", x.Cost),
                        Value = x.Cost.ToString()
                    }).ToList();

你必须使用.AsEnumerable() and the reason you can find from here

 db.ShippingMethods.AsEnumerable().Select(x => new SelectListItem()
                    {
                        Text = x.Name + " - " + String.Format("c", x.Cost),
                        Value = x.Cost.ToString()
                    }).ToList();

调用 AsEnumerable(或 ToList 或 ToArray)将 dbset 的内容拉入内存,在内存中可以对它们执行任何类型的操作。关于转换为存储表达式的消息意味着 linq 提供程序无法在数据库级别将 String.Format 转换为 SQL 和 运行。

在这种情况下,在 dbset 上调用 AsEnumerable 可能没问题,但在您不想将整个 table 拉入内存的情况下,您可以过滤它,然后列出它,然后转换它带有 select.

如果您考虑 性能 那么您可以按所示使用它 below.B 因为如果我们检索与 ShippingMethods table 来自 db,然后在内存上执行 projection(在 .AsEnumerable() 之后)意味着它会降低性能 heavily.Below query is suitable for the devs谁在考虑 EF 查询的性能。

AsEnumerable()

将每条记录加载到application memory,然后执行filtering等(例如Where/Take/Skip)。它将select * from MyTable, into the内存, then select the前X个元素`。

db.ShippingMethods.Select(x => new 
                    {
                        Name = x.Name,
                        Cost = x.Cost,
                    }).AsEnumerable().Select(y => new SelectListItem()
                    {
                        Text = y.Name + " - " + String.Format("c", y.Cost),
                        Value = y.Cost.ToString()
                    }).ToList();