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