getting identity row value using ADO.NET Entity

不想你离开。 提交于 2019-11-28 11:20:24

问题


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?


回答1:


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.
}



回答2:


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


来源:https://stackoverflow.com/questions/5831894/getting-identity-row-value-using-ado-net-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!