c# - 小巧玲珑 + MSAccess : How to get identifier of inserted row

标签 c# ms-access dapper

我在 C# 中使用 Dapper,后端是 MS Access。我的 DAL 方法在数据库中插入记录。我想返回插入行的唯一标识符(或更新的具有唯一标识符的 POCO)。 我期待我的功能如下(我知道这不起作用;只是为了解释我想要什么):-

public MyPoco Insert(MyPoco myPoco)
{
    sql = @"INSERT INTO MyTable (Field1, Field2) VALUES (@Field1, @Field2)";
    var param = GetMappedParams(myPoco);//ID property here is null.
    var result = _connection.Query<MyPoco>(sql, param, null, false, null, CommandType.Text);.Single();
    return result;//This result now contains ID that is created by database.
}

我来自 NHibernate 世界,POCO 使用 NH 自动更新。如果不;我们可以调用 Refresh 方法并更新 ID。 我不知道如何使用 Dapper 实现这一目标。

我读了this关于 SO 的问题与 SQL Server 无关。

另一个this问题没有可接受的答案。

我读了this接受的答案解释了使用 @@Identity 的问题。

最佳答案

这对我有用:

static MyPoco Insert(MyPoco myPoco)
{
    string sql = "INSERT INTO MyTable (Field1, Field2) VALUES (@Field1, @Field2)";
    _connection.Execute(sql, new {myPoco.Field1, myPoco.Field2});
    myPoco.ID = _connection.Query<int>("SELECT @@IDENTITY").Single();
    return myPoco;  // This result now contains ID that is created by database.
}

请注意,这将与连接到 Access 数据库的 OleDbConnection 配合使用,但不能OdbcConnection 配合使用。

编辑回复:评论

为了确保连接在 INSERT 和 SELECT 调用之间保持打开状态,我们可以这样做:

static void Insert(MyPoco myPoco)
{
    string sql = "INSERT INTO MyTable (Field1, Field2) VALUES (@Field1, @Field2)";
    bool connAlreadyOpen = (_connection.State == System.Data.ConnectionState.Open);
    if (!connAlreadyOpen)
    {
        _connection.Open();
    }
    _connection.Execute(sql, new {myPoco.Field1, myPoco.Field2});
    myPoco.ID = _connection.Query<int>("SELECT @@IDENTITY").Single();
    if (!connAlreadyOpen)
    {
        _connection.Close();
    }
    return;  // (myPoco now contains ID that is created by database.)
}

关于c# - 小巧玲珑 + MSAccess : How to get identifier of inserted row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37391883/

相关文章:

c# - Xamarin iOS 中无参数的绑定(bind)方法

c# - Access 2007 已锁定

当splitOn列不在子对象中时,Dapper多映射不返回空对象

C# 将 Dapper POCO 和 Dapper.Fluent EntityMap 作为参数传递

c# - 在 ASP.net 中动态添加控件时的 View 状态问题

c# - 我可以使用 Guid 的前 16 个或后 16 个字符并且它仍然是唯一的吗?

java - 将数百万条记录从本地插入Godaddy托管

c# - 我怎样才能让我的 dapper 结果成为一个列表?

c# - 在主表中创建具有重命名字段和非主键的实体关系

csv - 将分隔文件 (.csv) 中的行导入 MS-Access 表