执行使用EF5的Code First迁移的IDENTITY_INSERT(Performing an

2019-07-21 02:36发布

我有我试图通过代码第一次迁移,然后种子数据来创建一个POCO。 问题是,我想种时特定值插入到标识列。

这里是我的POCO

public class Result
{
    public long ResultId { get; set; }
    public long? TeamId { get; set; }

    public Team Team { get; set; }
}

这里是在Configuration.cs种子方法我AddOrUpdate调用

context.Results.AddOrUpdate
    (
         r => r.ResultId,
         new Result { ResultId = 101, TeamId = null },
         new Result { ResultId = 201, TeamId = null }
    );

正如预期的那样,它不插入的101和201的值,而是1和2有没有我可以向模型中的任何数据属性,以帮助这个?

Answer 1:

这如何通过属性/公约关闭身份

public class Result
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long ResultId { get; set; }
    public long? TeamId { get; set; }

    public Team Team { get; set; }
}

这是你如何通过EntityTypeConfiguration关闭身份

public class ResultMapper : EntityTypeConfiguration<Result>
{
    public ResultMapper()
    {
        HasKey(x => x.ResultId);
        Property(x => x.ResultId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    }
}

或者你也可以使用OnModelCreating超载

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Result>().Property(x => x.ResultId)
               .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    }


Answer 2:

如果有些人仍然感到困惑。 。 。

请参阅下面的人,让IDENTITY_INSERT与代码优先迁移种子工作所需的额外信息()方法

我没有用阿隆贯彻System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated属性设置模型ID的DB-生成的属性为“无”,但我仍然无法摆脱的标识插入误差。 我想我会在这里发布我的调查结果的情况下,其他人仍然有麻烦。

为了得到它的工作,我包种子法的逻辑在SQL交易并使用context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT myTable ON")允许在运行之前的插入.AddOrUpdate()方法。 这里是我的Configuration.vb文件(使用谷歌API类型作为我们的例子中的数据表):

Imports System
Imports System.Data.Entity
Imports System.Data.Entity.Migrations
Imports System.Linq

Namespace Migrations

    Friend NotInheritable Class Configuration 
        Inherits DbMigrationsConfiguration(Of DAL.MyDbContext)

        Public Sub New()
            AutomaticMigrationsEnabled = False
            AutomaticMigrationDataLossAllowed = False
        End Sub

        Protected Overrides Sub Seed(context As DAL.MyDbContext)
            '  This method will be called after migrating to the latest version.

            Dim newContext As New MyDbContext(context.Database.Connection.ConnectionString)
            Using ts = newContext.Database.BeginTransaction()

                Try

                    ' Turn on identity insert before updating
                    newContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT GoogleApiTypeGroups ON")
                    ' Make sure the expected GoogleApiTypeGroups exist with the correct names and IDs.
                    newContext.GoogleApiTypeGroups.AddOrUpdate(
                        Function(x) x.Id,
                        New GoogleApiTypeGroup() With {.Id = 1, .name = "Google Cloud APIs"},
                        New GoogleApiTypeGroup() With {.Id = 2, .name = "YouTube APIs"},
                        New GoogleApiTypeGroup() With {.Id = 3, .name = "Google Maps APIs"},
                        New GoogleApiTypeGroup() With {.Id = 4, .name = "Advertising APIs"},
                        New GoogleApiTypeGroup() With {.Id = 5, .name = "Google Apps APIs"},
                        New GoogleApiTypeGroup() With {.Id = 6, .name = "Other popular APIs"},
                        New GoogleApiTypeGroup() With {.Id = 7, .name = "Mobile APIs"},
                        New GoogleApiTypeGroup() With {.Id = 8, .name = "Social APIs"})
                    ' Attempt to save the changes.
                    newContext.SaveChanges()
                    ' Turn off the identity insert setting when done.
                    newContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT GoogleApiTypeGroups OFF")

                    ' Turn on identity insert before updating
                    newContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT GoogleApiTypes ON")
                    ' Make sure the expected GoogleApiTypes exist with the correct names, IDs, and references to their corresponding GoogleApiTypeGroup.
                    newContext.GoogleApiTypes.AddOrUpdate(
                        Function(x) x.Id,
                        New GoogleApiType() With {.Id = 1, .name = "Google Maps JavaScript API", .GoogleApiTypeGroupId = 3})
                    ' Save the changes
                    newContext.SaveChanges()
                    ' Turn off the identity insert setting when done.
                    newContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT GoogleApiTypes ON")

                    ts.Commit()
                Catch ex As Exception
                    ts.Rollback()
                    Throw
                End Try
            End Using

        End Sub

    End Class

End Namespace


Answer 3:

研究到在此之后,它看起来像如果密钥是以前创建,然后添加[DatabaseGenerated(DatabaseGeneratedOption.None)在迁移它不会真正做你想要什么,你可以通过访问数据库浏览器表检查本 - >键 - > PK - >修改和请参见Identity规格设置为是,而不是号

如果是这样的情况下,尝试迁移到一个点,该表不存在,然后重新迁移备份。



Answer 4:

如果您正在使用AutoMapper和使用/的foreach模式,则必须重新映射在for循环。

例:

foreach (var item in Ids) {
    var page = Mapper.Map<Pages>(model);
    .
    .
    .
    .
    db.Pages.Add(page);
}
db.SaveChanges();


文章来源: Performing an IDENTITY_INSERT using EF5 Code First Migrations