使用ADO.NET实体获取标识行值

时间:2011-04-29 12:16:25

标签: entity-framework-4 ado.net-entity-data-model

我在SQL Server 2008数据库中有以下表格:

User
--------------------------------------------------------
Id           Numeric(18, 0) | Identity(1, 1) PK not null
Name         Nchar(20)      | Not null

我正在使用ADO.NET实体数据模型:

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();
}

如何为新用户添加User.Id?

2 个答案:

答案 0 :(得分:2)

如果您的模型配置正确并且您的Id属性标有StoreGeneratedPattern.Identity,则只需将其命名为:

    var user = new User()
    {
        Name = userName
    };
    entities.User.AddObject(user);
    resultCode = 1;
    entities.SaveChanges();
    int id = user.Id; // it's here

答案 1 :(得分:1)

尝试保留对用户对象的引用。调用SaveChanges()后,应自动更新Id。以下是对代码的修改以演示:

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