I am trying to sort a child-collection with the Entity Framework. This is my code:
var query = db.Category
.Where(p => p.parrent_id == null)
.OrderByDescending(x => x.prefix)
.Select(o => new
{
开发者_如何学Go 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()
});
the ToEntityCollection method looks like this:
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;
}
I am getting the following error:
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.
on
es.Add(e);
Thanks in advance!
this has been asked before: Error Using ADO.NET Entity Framework
See here for why Attach rather than Add should work: http://msdn.microsoft.com/en-us/data/jj592676.aspx
You can't attach entities to a different context when they are attached to a different one. You need to detach it from the previous one if you relay want to do it. http://msdn.microsoft.com/en-us/library/bb896271.aspx
精彩评论