【问题标题】:LINQ Error: Method not recognizedLINQ 错误:方法无法识别
【发布时间】:2011-09-02 13:39:26
【问题描述】:

我使用以下代码编译没有问题,但是当我调用该方法时出现此错误:

LINQ to Entities 无法识别方法“System.String ToString()”方法,并且该方法无法转换为存储表达式。

public IEnumerable<string> GetAllCitiesOfCountry(int id)
    {
        var ad = from a in entities.Addresses
                 where a.CountryID == id
                 select a.City.Distinct().ToString();
        var fa = from b in entities.FacilityAddresses
                 where b.CountryID == id
                 select b.City.Distinct().ToString();
        return ad.Concat(fa).Distinct();
    }

如何重写才能工作?

【问题讨论】:

  • City 属性的类型是什么?

标签: c# .net linq linq-to-entities


【解决方案1】:

更新 - 我认为这就是您正在寻找的内容

public IEnumerable<string> GetAllCitiesOfCountry(int id)
    {
        var ad = from a in entities.Addresses
                 where a.CountryID == id
                 select a.City;
        var fa = from b in entities.FacilityAddresses
                 where b.CountryID == id
                 select b.City;
        return ad.Union(fa).Distinct();
    }

【讨论】:

    【解决方案2】:

    City 是什么类型?如果它已经是一个字符串,只需删除 .Distinct().ToString() 调用。如果是复杂类型,从类型中选出城市名称。

    更新:根据您的评论,您应该放弃 Distint() 和 ToString() 调用。城市名称集合的最终联合应该为您提供唯一的城市名称。

    public IEnumerable<string> GetAllCitiesOfCountry(int id) 
    { 
        var ad = from a in entities.Addresses 
                 where a.CountryID == id 
                 select a.City;
        var fa = from b in entities.FacilityAddresses 
                 where b.CountryID == id 
                 select b.City;
        return ad.Union(fa);
    } 
    

    【讨论】:

    • +1。如果它是一个字符串,你在上面调用Distinct 做什么?
    • City 是字符串,但如果我删除 ToString(),我会在返回 .Concat() 时收到从 的转换错误
    • @Stripling - 绝对正确,如果它是一个字符串,则不需要 Distinct 或 ToString 调用。我已经根据 cmets 进行了更新。
    • 现在我想多了,我敢打赌他打算让Distinct 应用于整个查询,而不是City。但既然他在Concat 之后打电话给Distinct,那就没有意义了。
    • @tvanfosson 谢谢它的工作。使用 concat() 或 Union() 有什么区别吗?
    猜你喜欢
    • 2014-11-16
    • 2013-06-04
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多