getting identity row value using ADO.NET Entity

2020-02-15 04:30发布

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?

2条回答
beautiful°
2楼-- · 2020-02-15 05:00

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
查看更多
一纸荒年 Trace。
3楼-- · 2020-02-15 05:03

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.
}
查看更多
登录 后发表回答