簡體   English   中英

如何在 FluentMigrator 中獲取最后插入的 id

[英]How to get last inserted id in FluentMigrator

我將 FluentMigrator 與 MySql 和 C# 一起使用。

[Migration(3)]
public class _0003_TestMigrationTI : Migration
{
    public override void Up()
    {
        Insert.IntoTable("cmn_file_types").Row(new { Name = "Image", Code = "IMG" });

        ???
    }
}

如何在相同的 Up() 方法中在 Insert.IntoTable 之后獲取最后插入的 id? ID 是 cmn_file_types 表中的一個 INT PRIMARY AUTO_INCREMENT 列。

MigrationBase class 具有 ConnectionsString 屬性。 只需使用它創建您的 ADO.net 查詢:

var builder = new SqlConnectionStringBuilder(ConnectionString);
var query = "SELECT IDENT_CURRENT('Table')"    

using (var connection = new SqlConnection(builder.ConnectionString))
{
    connection.Open();
    var command = new SqlCommand(query, connection);
    var lastId = command.ExecuteScalar();
    connection.Close();
}

更新:

試試這個。 為我工作。 在這里,您將獲得與新查詢相同的事務,這與 ADO 的情況不同。 所以“選擇 IDENT_CURRENT”會顯示未提交的當前 ID。

Execute.WithConnection((IDbConnection connection, IDbTransaction transaction) =>
            {
                var command = connection.CreateCommand();
                command.Transaction = transaction;
                command.CommandText = @"select IDENT_CURRENT('TestTable1')";
                var count = command.ExecuteScalar();
            });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM