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
});
resultCo开发者_JAVA百科de = 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:
var user = new User()
{
Name = userName
};
entities.User.AddObject(user);
resultCode = 1;
entities.SaveChanges();
int id = user.Id; // it's here
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:
if (entities.User.Count(u => u.Name == userName) == 0)
{
User newUser = new User()
{
Name = userName
};
entities.User.AddObject(newUser);
resultCode = 1;
entities.SaveChanges();
// newUser.Id should be populated at this point.
}
精彩评论