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

后端 未结 2 588
旧时难觅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:47

    One optimization of your code is to use AsEnumerable() after the Where method. If not, every entity is returned from storage, and the entire table is examined using LINQ to Objects. With this simple modification of your code you let the where clause run on sql and retrieve less records from storage. The general rule is to place any query clauses that are implemented by the LINQ provider first.

    using (DBContext context = new DBContext())
    {
        myCollection = context.Items.Where(i => i.Type == 1)
           .AsEnumerable().OrderBy(k => k.Name).Select(w => new
            {
                Alias = w.Name + string.Format("{0}", w.Id),
                Name = w.Name                        
            }).ToArray();
    }
    

提交回复
热议问题