c# – 使用EF5 Code First Migrations执行IDENTITY_INSERT

我有一个POCO,我试图通过Code First Migrations创建,然后播种数据.问题是我想在播种时将特定值插入标识列.

这是我的POCO

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

    public Team Team { get; set; }
}

这是我在Configuration.cs的Seed方法中的AddOrUpdate调用

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

正如预期的那样,它不会插入101和201的值,而是插入1和2.是否有任何DataAttributes我可以应用于模型来帮助解决这个问题?

这是如何通过属性/约定关闭Identity

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

    public Team Team { get; set; }
}

这是通过EntityTypeConfiguration关闭Identity的方法

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);
    }
翻译自:https://stackoverflow.com/questions/15258571/performing-an-identity-insert-using-ef5-code-first-migrations

转载注明原文:c# – 使用EF5 Code First Migrations执行IDENTITY_INSERT