Reputation: 8245
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?
Upvotes: 0
Views: 1592
Reputation: 25370
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
Upvotes: 2
Reputation: 17680
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.
Upvotes: 1