2011-07-07 4 views
1

Entity Frameworkで子コレクションをソートしようとしています。これは私のコードです:ObjectContextに添付されているオブジェクトを、ソースオブジェクトに関連付けられていないEntityCollectionに追加する方法

 var query = db.Category 
      .Where(p => p.parrent_id == null) 
      .OrderByDescending(x => x.prefix) 
      .Select(o => new 
      { 
       Category = o, 
       SubCategories = o.Category1.OrderBy(h => h.prefix) 
      }); 

     IEnumerable<Category> cats = query.AsEnumerable() 
      .Select(x => new Category 
      { 
       category_id = x.Category.category_id, 
       parrent_id = x.Category.parrent_id, 
       category_name = x.Category.category_name, 
       prefix = x.Category.prefix, 
       Category1 = x.SubCategories.ToEntityCollection() 
      }); 

ToEntityCollection方法は、次のようになります。

 public static EntityCollection<T> ToEntityCollection<T>(this IEnumerable<T> source) where T : class 
    { 
     var es = new EntityCollection<T>(); 
     foreach (T e in source) 
     { 
      es.Add(e); 
     } 
     return es; 
    } 

私は、次のエラーを取得しています:中

System.InvalidOperationException: The object could not be added to the EntityCollection or EntityReference. An object that is attached to an ObjectContext cannot be added to an EntityCollection or EntityReference that is not associated with a source object. 

es.Add(e); 

に感謝を前進!

+0

私は自分のためにまったく同じ拡張メソッドを書いて、同じ問題に出くわしました。私はエンティティを読み込むために同じコンテキストを使用していますが、私はまだエラーを受け取ります。あなたは解決策を見つけましたか? –

答えて

-2

エンティティを別のコンテキストにアタッチしても、エンティティを別のコンテキストにアタッチすることはできません。リレーしたい場合は、前のものから切り離す必要があります。 http://msdn.microsoft.com/en-us/library/bb896271.aspx

+0

コード内でどこを切り離すべきですか?私はquery.ToList.Foreach(q => db.Detach(q));を試しました。そして、私はこのエラーが表示されます:System.InvalidOperationException:ObjectStateManagerにアタッチされていないため、オブジェクトをデタッチできません。 – Nanek

関連する問題