Linq to Entities无法识别字符串.格式或串联"+" [英] Linq to Entities does not recognize string.Format or concatenation '+'

查看:60
本文介绍了Linq to Entities无法识别字符串.格式或串联"+"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

在运行时,尝试连接字符串并尝试将整数w.Id转换为字符串时出现错误.

In runtime i get an error when trying to concatenate the strings and trying con convert integer w.Id to string.

错误说:

Linq实体无法识别方法字符串.格式

Linq to entities does not recognize method string.Format

还不支持加号"+".

also plus concatenation sign '+' is not supported.

我已经通过引入AsEnumerable解决了这个问题:

I have solved this by introducing AsEnumerable:

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

但是我想知道这是否是最好的解决方案,或者还有另一种更适合这样做的方法.想法?

but I would like to know if this is the best solution or there is another way more suitable for doing this. Ideas?

推荐答案

代码的一种优化是在Where方法之后使用AsEnumerable().如果不是,则从存储中返回每个实体,并使用LINQ to Objects检查整个表.通过对代码的简单修改,可以让where子句在sql上运行,并从存储中检索较少的记录.一般规则是首先放置由LINQ提供程序实现的所有查询子句.

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();
}

这篇关于Linq to Entities无法识别字符串.格式或串联"+"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆