2010-05-12 18 views
0

我無法弄清楚我做錯了什麼。我有以下方法:使用Linq To Entities訪問多對多時調用ToList()時編譯時出錯

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

     return members.ToList<WObject>(); 
    } 

這將返回以下錯誤:

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>'

我怎麼能在EntityCollection轉換到一個列表,而不延遲加載?

回答

1

看起來您的查詢正在返回一系列實體集合 - 實體列表的列表,就像它一樣。如果你想扁平它們。你試圖將它轉換成實體列表。現在,你想怎麼做?你想把所有的收藏品放在一個大列表中嗎?或者從每個集合中獲取第一個條目?這裏有一個例子可以使結果變得平坦:

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

這個工作,並且合理。謝謝! – KallDrexx 2010-05-12 03:45:51