如何将附加到ObjectContext的对象添加到与源对象不关联的EntityCollection

本文关键字:对象 关联 EntityCollection 添加 ObjectContext | 更新日期: 2023-09-27 18:01:30

我正在尝试用实体框架排序子集合。这是我的代码:

        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);

提前感谢!

如何将附加到ObjectContext的对象添加到与源对象不关联的EntityCollection

这个问题之前已经问过了:错误使用ADO。. NET实体框架

请参阅此处了解为什么要使用Attach而不是Add: http://msdn.microsoft.com/en-us/data/jj592676.aspx

当实体被附加到另一个上下文时,不能将它们附加到另一个上下文。如果你想做的话,你需要将它与前一个分离。http://msdn.microsoft.com/en-us/library/bb896271.aspx