Mediator
Mediator

Reputation: 15378

How get array in linq to entity?

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.

Upvotes: 0

Views: 5757

Answers (2)

Simon_Weaver
Simon_Weaver

Reputation: 145950

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

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160892

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.

Upvotes: 5

Related Questions