views:

539

answers:

1

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.

A: 

Assuming that there is a 1 to Many relationship between User and C, you may want to use a different syntax to add a C to the parent User. Instead of tempC.User = previously loaded user; you probably want to add the tempC as a child of User. Here is what I mean:

C tempC = new C(); 
(previously created user).C.Add(tempC);
Context.AddToCSet(tempC);
YeahStu