Let me describe the behavior I get:
- Load a user from the database: this means the user is attached to the context
- Create a new Object C:
- C tempC = new C();
- tempC.User = previously loaded user;
- Context.AddToCSet( tempC );
- The last line throws an exception because the object was added to the context when the property user was set.
but if I do the following:
- Load a user from the database: this means the user is attached to the context
- Create a new Object C:
- C tempC = new C();
- tempC.User = previously loaded user;
- Context.SaveChange();
- Create a new Object E which has a relationship with Object C.
- E tempE = new E();
- tempE.C = previously created C;
- Context.AddToESet( tempE );
it doesn't throw an exception. I was expecting an exception because by then C is attached to the context, which should be the same case as the first example. But it isn't. Why, and what can I do to have some consistency?
I am planning on checking the state of the object (EntityState == Detached) before adding it to the set, but I figured I must be doing something wrong to begin with.