2014-06-11 21 views
3

在迁移过程中,我如何插入到我的表中,然后检索该标识,然后使用它将相关数据插入到另一个表中。如何在迁移过程中检索插入的标识FluentMigrator

我现在拥有的是一个hardoced 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 
    }); 

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

我使用SQL服务器,如果是任何帮助......

我认为这将是微不足道的,但好像不是,google搜索它,这里没有任何seing应答后。

+0

我不确定这是否适用于'fluent-migrator'的上下文中,但是你看过'@@ IDENTITY'吗? (这是一个tsql系统函数。)http://msdn.microsoft.com/en-us/library/ms187342(v=sql.105).aspx – DMason

+0

@DMason我知道如何在SQL中完成它,我想要什么知道如何用FluentMigrator来做到这一点。或者如何在使用fluentmigrator插入后获得@@ Identity选择 –

+0

自从我使用FluentMigrator代码以来,我已经有一段时间了,但在快速浏览之后,我看不到一种方法来执行此操作,所以它必须是一个新功能。我不确定您对代码的熟悉程度,但您可以对https://github.com/schambers/fluentmigrator/blob/master/src/FluentMigrator.Runner/Generators/SqlServer/SqlServerQuoter.cs进行更改类,如果你放入@@ IDENTITY,它不会尝试把它当作一个字符串。 – Castrohenge

回答

0

我在SQL查询使用Execute.Sql()@@IDENTITY对同一案件

+0

Execute.Sql()返回一个void,所以您将无法从执行的语句中获取标识。 – krillgar

+0

我的意思是将@@ IDENTITY用于sql-query:Execute.Sql(“Insert ...; Insert ... values(@@ IDENTITY,...)”)。如果你想在c#代码中使用标识 - 你可以使用Dapper例如:int id = connection.Query (“Select @@ IDENTITY”)。Single(); – razon

1

您可以通过您的.Row()电话后链接.WithInsertIdentity()手动插入的ID。

这将让你保存在内存中作为外键在其他对象中使用。不幸的是,直到Up()Down()方法中的所有代码完成执行之后,FluentMigrator才会真正执行任何SQL。

相关问题