Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdating a relationship in Entity Framework generates SQL error
    primarykey
    data
    text
    <p>I'm getting headaches here. I've got a <strong>one to zero-or-one</strong> relationship between a Session and a User object, designed in Entity Framework 4 using the model first approach.</p> <ul> <li>A User <strong>should</strong> have a session (<em>one</em>)</li> <li>A Session <strong>can</strong> have a User (<em>zero-to-one</em>).</li> </ul> <p>So, in runtime I pull a session from the database using</p> <pre><code>Session session = context.Sessions.FirstOrDefault(s =&gt; s.Token.Equals(token)); </code></pre> <p>and after that I create a user, created based on user input like this</p> <pre><code>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(); </code></pre> <p>and when I save, the SQL server throws an exception telling me that the GUID I try to <strong>insert</strong> in the database already exists, because yeah, it does. The problem is, that it <strong>shouldnt</strong> insert, it should <strong>update</strong> the session and fill the forein key that belongs with it. <em>The foreign key resides on the User side of the relation, this is alright, right?</em></p> <p><strong>edit</strong> The user <em>should</em> 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.</p> <p>Here's a chronological list of what should be done:</p> <ul> <li>Session gets created</li> <li>Session gets saved</li> <li>Session gets selected from the database</li> <li>User gets created</li> <li>User &lt;-> Session relations gets set</li> <li>User gets saved</li> </ul> <p>And what I get is:</p> <p><strong>Violation of PRIMARY KEY constraint 'PK_Sessions'. Cannot insert duplicate key in object 'dbo.Sessions'. The duplicate key value is <em>VALUE</em>. The statement has been terminated.</strong></p> <p>Please help me out, I've been fiddling with this for the past 2 hours.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload