Search code examples
c#linq-to-sqlusing

Return ID after insert with LINQ to SQL


i know there are numerous topics already concerning this, since i googled it already but none of them can fit/work with my code as far as i can see. I simply want to return an Auto Generated ID form my database after an insert. This is a part of my code:

    using (***LINQDataContext dc = new ***LINQDataContext())
    {
        dc.Users.InsertOnSubmit(new User
        {
            Username = user,
            Password = EncryptPassword(user, pass, 1, null, null),
            Email = email
        });

        dc.SubmitChanges();

        return true;
    }

Solution

  • var newUser = new User {
        Username = user,
        Password = EncryptPassword(user, pass, 1, null, null),
        Email = email
    };
    dc.Users.InsertOnSubmit(newUser);
    dc.SubmitChanges();
    // any identity / rowversion properties should now have values
    var id = newUser.Id;