C# MySQL数据适配器版本6.1.3.0在版本5数据适配器工作时未返回ID
我最近将MySQL数据适配器从v5升级到v6。当我使用v5 MySQL数据适配器时,下面的代码工作得非常好。但是,由于我已经开始使用数据适配器的v6,当我添加新记录时,它不会返回记录的新ID。有人知道一个优雅的方法来实现这一点吗C# MySQL数据适配器版本6.1.3.0在版本5数据适配器工作时未返回ID,c#,mysql,C#,Mysql,我最近将MySQL数据适配器从v5升级到v6。当我使用v5 MySQL数据适配器时,下面的代码工作得非常好。但是,由于我已经开始使用数据适配器的v6,当我添加新记录时,它不会返回记录的新ID。有人知道一个优雅的方法来实现这一点吗 protected void SetRecord(ref T Data, string Sql) { // // Get a connection to use // string connecti
protected void SetRecord(ref T Data, string Sql)
{
//
// Get a connection to use
//
string connectionKey = "";
MySqlConnection Connection = ConnectionManager.Current.OpenConnection(out connectionKey);
MySqlDataAdapter da;
MySqlCommandBuilder cb;
DataTable dt = new DataTable();
DataRow dr;
da = new MySqlDataAdapter(Sql, Connection);
da.Fill(dt);
//
// If there is more than one row, then edit 1st row, else add new row
//
if (dt.Rows.Count > 0)
{
dr = dt.Rows[0];
DatabaseRow_Set(ref dr, Data);
//
// Update the DataSet with the Database
//
cb = new MySqlCommandBuilder(da);
da.Update(dt);
}
else
{
dr = dt.NewRow();
DatabaseRow_Set(ref dr, Data);
dt.Rows.Add(dr);
//
// Update the DataSet with the Database
//
cb = new MySqlCommandBuilder(da);
da.Update(dt);
//
// Call get from data row to get new ID
//
DatabaseRow_Get(dr, ref Data);
}
//
// Close Connection
//
ConnectionManager.Current.CloseConnection(connectionKey);
}
我不明白为什么这个功能在v5中工作,而现在在v6中不工作。然而,我确实找到了一个解决办法
dr = dt.NewRow();
DatabaseRow_Set(ref dr, Data);
dt.Rows.Add(dr);
//
// Update the DataSet with the Database
//
cb = new MySqlCommandBuilder da);
da.Update(dt);
MySqlCommand cmd = new MySqlCommand("select LAST_INSERT_ID()", Connection);
long ID = ((long) cmd.ExecuteScalar());
DatabaseRow_GetID(ref Data, ID);