Dapper + MSAccess:如何获取插入行的标识符 [英] Dapper + MSAccess: How to get identifier of inserted row
问题描述
我正在使用带有C#的Dapper,后端是MS Access.我的DAL方法在数据库中插入记录.我想返回插入行的唯一标识符(或使用唯一标识符更新的POCO). 我期望我的功能如下(我知道这不起作用;只是为了解释我想要的):-
I am using Dapper with C# and back end is MS Access. My DAL method inserts record in database. I want to return unique identifier (or updated POCO with unique identifier) of the inserted row. I am expecting my function something like follows (I know this does not work; just to explain what I want): -
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实现这一目标.
I am from NHibernate world and POCO updates automatically with NH. If not; we can call Refresh method and it updates the ID. I am not aware how to achieve this with Dapper.
我阅读了这篇文章关于SO的问题,它与SQL Server无关.
I read this question on SO which is not relevant as it talks about SQL Server.
另一个此问题尚未接受答案.
Another this question does not have accepted answer.
我阅读了这个问题,在哪里接受了答案解释了使用@@Identity
的陷阱.
I read this question where accepted answer explains pit-falls of using @@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
一起使用不.
Note that this will work with an OleDbConnection
to the Access database, but it will not work with an OdbcConnection
.
编辑以下内容:评论
要确保INSERT和SELECT调用之间的连接保持打开状态,我们可以这样做:
To ensure that the Connection remains open between the INSERT and the SELECT calls, we could do this:
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.)
}
这篇关于Dapper + MSAccess:如何获取插入行的标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!