开发者

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

开发者 https://www.devze.com 2022-12-29 19:43 出处:网络
I can\'t figure out what I am doing wrong.I have the following method: public IList<WObject> GetRelationshipMembers(int relId)

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 开发者_JS百科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?


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

精彩评论

暂无评论...
验证码 换一张
取 消