0

So I've seen this...

Get Auto Identity Key after Insert via EF

Seems like a lot to go through and I notice DbContext.SaveChanges() returns int.

So what I want to know is, can't we just do something like this:

public string username { get; protected set; }
public string password { get; protected set; }

public int RegisterUser()
{
    DbContext.users u = new DbContext.users();
    if (!String.IsNullOrEmpty(username))
    {
        u.username = username;
    }
    if (!String.IsNullOrEmpty(password))
    {
        u.password = password;
    }

    DbContext.users.Add(u);
    return DbContext.SaveChanges();
}

Its not clear by the intellisense what the int value is that SaveChanges returns, so I'm just trying to figure out, is this a 0/1 value for "yes it worked" or "no it broke" or is this the id value of the new record?

Community
  • 1
  • 1
Ortund
  • 8,095
  • 18
  • 71
  • 139
  • The integer return value is: >The number of objects in an Added, Modified, or Deleted state when SaveChanges was called. – David Tansey Apr 30 '14 at 19:26
  • After you call `SaveChanges()`, your `u` object will have the updated Id property. The return value from `SaveChanges()` is the number of objects written to the database. – Troy Carlson Apr 30 '14 at 19:27

2 Answers2

2

after calling db.SaveChanges when inserting an item with an Identity Key, that object's ID will be set.

I.E. after you call db.SaveChanges, u.ID will be set

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
1

To get the ID (auto generated) you could check the user object.

u.ID //assuming it exists.

the int returned by SaveChanges() is the number of objects written to the underlying database.

scartag
  • 17,548
  • 3
  • 48
  • 52