【问题标题】:LINQ to Entities does not recognize the method 'System.String ToString()' method and this method cannot be translated into a store expressionLINQ to Entities 无法识别方法“System.String ToString()”方法,并且该方法无法转换为存储表达式
【发布时间】:2012-04-21 16:47:14
【问题描述】:

当我尝试运行以下代码时。

var result = from c in db.brand
             where c.title.contains("test")
             select c.title + "-" +c.brand;

List<string> lst = r.ToList();

它给出以下错误。

LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且这个方法不能翻译成store 表达。

【问题讨论】:

标签: c# asp.net linq


【解决方案1】:

我建议以匿名类型获取标题和品牌,然后在进程中执行字符串连接:

var list = db.Brand.Where(c => c.Title.Contains("test"))
                   .Select(c => new { c.Title, c.Brand })
                   .AsEnumerable() // Rest of the query in-process
                   .Select(x => x.Title + " " + x.Brand)
                   .ToList();

【讨论】:

    【解决方案2】:

    试试这个:

    var result = from c in db.brand where c.title.contains("test") select c;
    var finalResult = result.ToList().Select(ss=> ss.title + "-" + ss.brand);
    

    【讨论】:

    • 您需要再次致电ToList 以获取List&lt;string&gt;,这似乎是需要的。此外,当真正需要标题和品牌时,这将获取每个实体的所有属性。最后,不需要调用ToList 作为中间步骤——AsEnumerable 可以避免创建中间列表。
    • ToList 或 AsEnumerable 强制在字符串函数可用于收集之后对数据上下文执行查询。很好的乔恩,谢谢
    【解决方案3】:

    尝试:

    var result = from c in db.brand where c.title.contains("test") select new { c.title + "-" +c.brand }
    

    【讨论】:

    • 使用匿名类型在这里没有帮助 - 代码甚至无法编译,因为匿名类型中的属性没有名称。
    • 是的,你是对的。确实在这里吸取了教训:总是测试答案!
    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    相关资源
    最近更新 更多