Linq to Entities does not recognize string.Format or concatenation '+'

后端 未结 2 590
旧时难觅i
旧时难觅i 2020-12-09 18:14

I have below code:

using (DBContext context = new DBContext())
{
    myCollection = context.Items.Where(i => i.Type == 1).OrderBy(k => k.Name).Select(w         


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-09 18:45

    EF can't convert String.Format into SQL, but it handles string concatenations without problem. Use SqlFunctions.StringConvert instead of String.Format to convert number into string on server side:

    Select(w => new {
        Alias = w.Name + SqlFunctions.StringConvert((double)w.Id),
        Name = w.Name                        
    })
    

    It generates something like

    SELECT 
    [Extent1].[Name] + STR( CAST( [Extent1].[Id] AS float)) AS [C1], 
    [Extent1].[Name] AS [Name]
    FROM [dbo].[Items] AS [Extent1]
    

    UPDATE: Thus you are using EF provider which does not support this conversion (SQL CE provider cannot cannot translate this query into SQL) you have only one option left - move calculations to client side, as you already have done.

提交回复
热议问题