简体   繁体   English

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

[英]How to get last inserted id in FluentMigrator

I'm using FluentMigrator with MySql and C#.我将 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" });

        ???
    }
}

How to get last inserted id after Insert.IntoTable in the same Up() method?如何在相同的 Up() 方法中在 Insert.IntoTable 之后获取最后插入的 id? The ID is an INT PRIMARY AUTO_INCREMENT column in cmn_file_types table. ID 是 cmn_file_types 表中的一个 INT PRIMARY AUTO_INCREMENT 列。

MigrationBase class has ConnectionsString property. MigrationBase class 具有 ConnectionsString 属性。 Just use it creating your ADO.net query:只需使用它创建您的 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();
}

update:更新:

Try this one.试试这个。 Worked for me.为我工作。 Here you'll get the same transaction for your new query, unlike that case with ADO.在这里,您将获得与新查询相同的事务,这与 ADO 的情况不同。 So "select IDENT_CURRENT" will show you uncommited current Id.所以“选择 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