Search code examples
c#sql-serverfluent-migrator

How to retrieve inserted identity in migration of FluentMigrator


During a migration how do i Insert into my table, then retrieve the ID, and then use it to insert a related data in another table.

what i have now is an hardoced ID to insert, but I don't know what it's gonna be when i'll run the migration.

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

I'd like to be able to retrieve the inserted ID and use it for the second insert instead of harcoding it.

I'm using SQL Server if it's any help...

I Thought this would be trivial, but seems like it's not, after googling for it, and not seing any answers here.


Solution

  • I use Execute.Sql() with @@IDENTITY in sql-query for same cases