如何在 FluentMigrator 迁移中检索插入的身份

moi*_*eme 4 c# sql-server fluent-migrator

在迁移期间,如何插入到我的表中,然后检索 ID,然后使用它在另一个表中插入相关数据。

我现在拥有的是要插入的硬编码 ID,但我不知道运行迁移时它会是什么。

var contactId = 2;
var phoneNumber = 2;

Insert.IntoTable("Contacts")
    .WithIdentityInsert()
    .Row(new
    {
        Id = contactId,
        TimeZoneId = contact.TimeZoneId,
        contact.CultureId,
        Type = (byte)(int)contact.Type,
        Email = contact.Email.ToString(),
        EntityId = entityId
    });

 Insert.IntoTable("PhoneNumbers")
    .WithIdentityInsert()
    .Row(new
    {
        Id = phoneNumberId,
        phone.Number,
        Type = (byte)(int)phone.Type,
        ContactId = contactId
    });
Run Code Online (Sandbox Code Playgroud)

我希望能够检索插入的 ID 并将其用于第二次插入,而不是对其进行编码。

我正在使用 SQL Server,如果有帮助的话...

我认为这会是微不足道的,但在谷歌搜索之后似乎并非如此,并且在这里没有看到任何答案。

kri*_*gar 5

您可以在调用.WithInsertIdentity()后通过链接手动插入 ID .Row()

这将使您将其保留在内存中,以便在其他对象中用作外键。Up()不幸的是,FluentMigrator 在或Down()方法中的所有代码完成执行之前实际上不会执行任何 SQL 。