简体   繁体   中英

Select method in LINQ and converting int to string value

I have a method:

 public List<string> FooBar(int companyId, string countryCode)
        {
                return repository.GetAll().Where(x => countryCode == x.CountryCode && x.Services.Any(y => y.CompanyId == companyId)).Select(x => Convert.ToString(x.Id)).ToList();
        }

I also tried .Select(x => x.Id.ToString())

Im getting runtime error as follows:

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

Because you are doing it while the query is not yet materialized (it means it's not in the memory yet). This means that you are calling .ToList() after you are done with the conversion. If you want to convert to a string before materializing (in SQL), you need to use SqlFunctions like SqlFunctions.StringConvert .

What you can do is call .ToList() and then take .Select(y=>y.Id.ToString()).ToList() or use the previous method.

Try this:

 var q= repository.GetAll().Where(x => countryCode == x.CountryCode && x.Services.Any(y => y.CompanyId == companyId)).Select(x => x.Id).ToList();

return  q.Select(x => x.ToString()).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM