How to get last inserted id in FluentMigrator

930 Views Asked by At

I'm using FluentMigrator with MySql and C#.

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

        ???
    }
}

How to get last inserted id after Insert.IntoTable in the same Up() method? The ID is an INT PRIMARY AUTO_INCREMENT column in cmn_file_types table.

1

There are 1 best solutions below

2
ba-a-aton On

MigrationBase class has ConnectionsString property. Just use it creating your ADO.net query:

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();
}

update:

Try this one. Worked for me. Here you'll get the same transaction for your new query, unlike that case with ADO. So "select IDENT_CURRENT" will show you uncommited 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();
            });