在linq中将int转换为字符串以进行搜索

Gor*_*ake 7 c# linq asp.net entity-framework

我希望我的用户能够通过部分字符串搜索采购订单(这是INT的),即如果采购订单是123456,则输入456会在结果中输入123456.

我认为这会奏效:

        var pop = (from po in ctx.PurchaseOrders
               let poid = po.PurchaseOrderID.ToString()
               where poid.Contains(term)
               select new SearchItem
               {
                   id = poid,
                   label = po.SupplierID,
                   category = "purchaseorder"
               }).ToList();
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
Run Code Online (Sandbox Code Playgroud)

如何将INT PurchaseOrderID转换为字符串以使我能够搜索它的片段?

谢谢

Bap*_*tta 14

用这个:

id = SqlFunctions.StringConvert((double)poid)
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请访问:http://msdn.microsoft.com/en-us/library/dd487127.aspx

  • 这会奏效.但它引入了代码和后端数据库之间的依赖关系(如果EF提供程序是Sql Server,SqlFunctions将起作用),这可能是也可能不是问题. (4认同)

Gor*_*ake 5

为了将来参考,已使用以下方法修复此问题:

    var pop = ctx
    .PurchaseOrders
    .OrderBy(x => x.PurchaseOrderID)
    .ToList()
    .Select(x => new SearchItem()
    {
        id = x.PurchaseOrderID.ToString(),
        label = x.SupplierID,
        category = "purchaseorder"
    });
Run Code Online (Sandbox Code Playgroud)

是中间人名单使其发挥作用。

  • 我一直在使用 SqlFunctions.StringConvert,但我真的不喜欢创建依赖项。感谢您提供此解决方案! (2认同)