How get array in linq to entity?

喜欢而已 提交于 2019-12-12 04:59:37

问题


var sites = 
    from country in db.Countries
    select new SitiesViewByUser()                
    {         
        Country = country.Title, 
        City = country.Cities
            .Select(m => m.Title).ToArray()                                   
    };

City - array string.

I need get array Cities.Title

this code:

foreach(var item in sites)

get this error:

Expression of LINQ to Entities does not recognize the method "System.String [] ToArray [String] (System.Collections.Generic.IEnumerable` 1 [System.String]) ", so it can not be converted into an expression store.


回答1:


You should be able to project to an anonymous type, then use ToArray() once you are back in Linq to objects land by using AsEnumerable():

var sites = 
    (from country in db.Countries
    select new 
    { 
         Country = country.Title,
         Cities = country.Cities.Select(m => m.Title)
    })
    .AsEnumerable()
    .Select(country => new SitiesViewByUser()
    {         
        Country = country.Title, 
        City = country.Cities.ToArray()
    };

The problem is that ToArray() is simply not defined for the Linq to Entities IQueryable provider (what would be the equivalent call in SQL?). Hence you have to grab your results, switch to Linq to Objects and then you can materialize them as needed.




回答2:


Use ToList() instead. You can make the type of your property ICollection<T> which represents a list of items with a known count.

ToList() was added for EF 6 in this work item http://entityframework.codeplex.com/workitem/808



来源:https://stackoverflow.com/questions/9446826/how-get-array-in-linq-to-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!