gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:21:32 26 4
gpt4 key购买 nike

我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com