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

时间:2011-07-07 09:28:56

标签: c# .net entity-framework-4

我正在尝试使用Entity Framework对子集合进行排序。这是我的代码:

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

提前致谢!

2 个答案:

答案 0 :(得分:0)

之前已经问过:Error Using ADO.NET Entity Framework

请参阅此处了解为什么附加而不是添加应该有效:http://msdn.microsoft.com/en-us/data/jj592676.aspx

答案 1 :(得分:-2)

当实体附加到不同的上下文时,您无法将实体附加到其他上下文。如果你想要继续它,你需要将它从前一个分离。 http://msdn.microsoft.com/en-us/library/bb896271.aspx