Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 840
moi_meme Avatar asked Oct 18 '25 23:10

moi_meme


1 Answers

You are able to manually insert the Id by chaining .WithInsertIdentity() after your .Row() call.

This will let you keep it in memory for use within other objects as Foreign Keys. Unfortunately, FluentMigrator doesn't actually execute any SQL until after all code within the Up() or Down() methods finish executing.

like image 172
krillgar Avatar answered Oct 21 '25 14:10

krillgar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!