2011-09-02 149 views
1

我使用下面的代码编译没有问题,但是当我打电话的方法,我得到这个错误:LINQ错误:方法无法识别

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

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

怎样才可以重新编写,以便上班?

+0

什么是城市属性的类型? – StriplingWarrior

回答

3

什么类型是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

+1。如果它是一个字符串,你在做什么叫'Distinct'? – StriplingWarrior

+0

城市是字符串,但如果我放弃ToString()我得到一个转换错误从返回.Concat() – Tsarl

+0

@Stripling - 绝对正确,如果它是一个字符串,你不需要Distinct或ToString调用。我已根据评论进行了更新。 – tvanfosson

4

更新 - 我认为这是你在找什么

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

+1感谢它的工作。 – Tsarl

相关问题