I have the following table in SQL Server 2008 database:
User
--------------------------------------------------------
Id Numeric(18, 0) | Identity(1, 1) PK not null
Name Nchar(20) | Not null
I'm using an ADO.NET Entity Data model to do:
MyEntities entities;
try
{
entities = new MyEntities();
if (entities.User.Count(u => u.Name == userName) == 0)
{
entities.User.AddObject(new User()
{
Name = userName
});
resultCode = 1;
entities.SaveChanges();
}
else
{
resultCode = 2;
}
}
catch
{
resultCode = 3;
}
finally
{
if (entities != null)
entities.Dispose();
}
How can I get User.Id for new User added?
If your model is configured correctly and you have Id property marked with
StoreGeneratedPattern.Identity
you need simply call this:Try keeping a reference to the user object. Once SaveChanges() is called, the Id should automatically be updated. Here's a modification of your code to demonstrate: