KallDrexx
KallDrexx

Reputation: 27803

Compile error when calling ToList() when accessing many to many with Linq To Entities

I can't figure out what I am doing wrong. I have the following method:

    public IList<WObject> GetRelationshipMembers(int relId)
    {
        var members = from r in _container.ObjectRelationships
                      where r.Id == relId
                      select r.WObjects;

        return members.ToList<WObject>();
    }

This returns the following error:

Instance argument: cannot convert from 'System.Linq.IQueryable<System.Data.Objects.DataClasses.EntityCollection<Project.DomainModel.Entities.WObject>>' to 'System.Collections.Generic.IEnumerable<Project.DomainModel.Entities.WObject>'

How can I convert the EntityCollection to a list without lazy loading?

Upvotes: 0

Views: 278

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499800

It looks like your query is returning a sequence of entity collections - a list of lists of entities, as it were. If you want to flatten them. You're trying to convert it into just a list of entities. Now, how do you want to do that? Do you want to flatten all the collections into one big list? Or take the first entry from each collection? Here's an example which will flatten the results:

public IList<WObject> GetRelationshipMembers(int relId)
{
    var members = from r in _container.ObjectRelationships
                  where r.Id == relId
                  select r.WObjects;

    return members.SelectMany(x => x)
                  .ToList<WObject>();
}

Upvotes: 1

Related Questions