G. Goncharov
G. Goncharov

Reputation: 302

Adding entity to Collection removes it from another (Entity Framework)

guys, I've got very strange problem, that nobody from my company knows.

I have a Collection inside one object, which I created manualy:

Cost cost = new Cost 
        {
            ...
        };
cost.Formulas.Add(new Formula()
                {
                    CostID = cost.ID,
                    FieldName = "Distance",
                    Formula1 = "12+2",
                });

Next, I got another object with the same type and ID from context:

Cost updatingCost = context.Costs.Include("Formulas").FirstOrDefault(c => c.ID == cost.ID);

And finally I do:

updatingCost.Formulas.Add(cost.Formulas.ToList()[0]);

And here is magic! After that line cost.Formulas doesn't contains that Formula any more!!

cost.Formulas.Count = 0

What does this method iCollection.Add() do? Why it removes an object from other collection? It blows my mind, please help to understand it!

Upvotes: 1

Views: 48

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109089

In fact it is pretty simple. By adding the new formula to another Cost object, updatingCost, EF changes the foreign key value CostID to the value of updatingCost.ID.

This is because EF executes relationship fixup many times when entites are manipulated in code. This process makes sure that primitive ID values and object references and collection contents match.

Upvotes: 1

Related Questions