简体   繁体   中英

Updating a relationship in Entity Framework generates SQL error

I'm getting headaches here. I've got a one to zero-or-one relationship between a Session and a User object, designed in Entity Framework 4 using the model first approach.

  • A User should have a session ( one )
  • A Session can have a User ( zero-to-one ).

So, in runtime I pull a session from the database using

Session session = context.Sessions.FirstOrDefault(s => s.Token.Equals(token));

and after that I create a user, created based on user input like this

user = context.Users.Create();

user.GUID = Guid.NewGuid();
user.Username = username;
user.Firstname = firstname;
user.Lastname = lastname;
user.Session = session;

context.Users.Add(user);
context.SaveChanges();

and when I save, the SQL server throws an exception telling me that the GUID I try to insert in the database already exists, because yeah, it does. The problem is, that it shouldnt insert, it should update the session and fill the forein key that belongs with it. The foreign key resides on the User side of the relation, this is alright, right?

edit The user should be a new user. Updating the user is not what I'm trying to accomplish. Also, the error is because the code tries to insert the session with the same primary key value, instead of just updating it's foreing keys.

Here's a chronological list of what should be done:

  • Session gets created
  • Session gets saved
  • Session gets selected from the database
  • User gets created
  • User <-> Session relations gets set
  • User gets saved

And what I get is:

Violation of PRIMARY KEY constraint 'PK_Sessions'. Cannot insert duplicate key in object 'dbo.Sessions'. The duplicate key value is VALUE . The statement has been terminated.

Please help me out, I've been fiddling with this for the past 2 hours.

Edit: Changed my answer to reflect changed problem description :)

Make sure you always use the same context instance when handling these kind of updates.

What seemed to be happening here was that session was retrieved in one context, but the user was saved in another instance of that context. Therefore, in the new context, the session was seen as new and hence, it was insterted (wrongfully)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM