开发者

Copying from EntityCollection to EntityCollection impossible?

开发者 https://www.devze.com 2022-12-27 02:27 出处:网络
How would you do this (pseudo code): product1.Orders.AddRange(product2.Orders); However, the function \"AddRange\" does not exist, so how would you copy all items in the E开发者_如何学CntityCollectio

How would you do this (pseudo code): product1.Orders.AddRange(product2.Orders);

However, the function "AddRange" does not exist, so how would you copy all items in the E开发者_如何学CntityCollection "Orders" from product2 to product1?

Should be simple, but it is not...


The problem is deeper than you think.

Your foreach attempt fails, because when you call product1.Orders.Add, the entity gets removed from product2.Orders, thus rendering the existing enumerator invalid, which causes the exception you see.

So why does entity get removed from produc2? Well, seems quite simple: because Order can only belong to one product at a time. The Entity Framework takes care of data integrity by enforcing rules like this.

If I understand correctly, your aim here is to actually copy the orders from one product to another, am I correct?

If so, then you have to explicitly create a copy of each order inside your foreach loop, and then add that copy to product1.

For some reason that is rather obscure to me, there is no automated way to create a copy of an entity. Therefore, you pretty much have to manually copy all Order's properties, one by one. You can make the code look somewhat more neat by incorporating this logic into the Order class itself - create a method named Clone() that would copy all properties. Be sure, though, not to copy the "owner product reference" property, because your whole point is to give it another owner product, isn't it?

Anyway, do not hesitate to ask more questions if something is unclear. And good luck.

  • Fyodor


Based on the previous two answers, I came up with the following working solution:

public static void AddRange<T>(this EntityCollection<T> destinationEntityCollection,
                                       EntityCollection<T> sourceEntityCollection) where T : class  
    {
        var array = new T[sourceEntityCollection.Count()];

        sourceEntityCollection.CopyTo(array,0);


        foreach (var entity in array)
        {
            destinationEntityCollection.Add(entity);
        }
    }


Yes, the usual collection related functions are not there.

But,
1. Did you check CopyTo method?
2. Do you find any problem with using the iterator? You know, GetEnumerator, go through the collection and copy the entities?

The above two can solve your problems. But, I'm sure in .NET 3.0+ there would be compact solutions.

My answers are related to .NET 2.0

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号