Copying from EntityCollection to EntityCollection impossible?

后端 未结 3 849
我在风中等你
我在风中等你 2021-01-22 22:13

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

相关标签:
3条回答
  • 2021-01-22 22:41

    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 讨论(0)
  • 2021-01-22 22:42

    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);
            }
        }
    
    0 讨论(0)
  • 2021-01-22 22:44

    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
    0 讨论(0)
提交回复
热议问题