簡體   English   中英

使用代碼優先EF 6運行Seed方法時出錯

[英]Error when running Seed method using code first EF 6

我試圖運行update-database命令在數據庫中插入一些初始數據,但出現錯誤。 這是我的課:

[Table("NotAllowedDomain")]
public class NotAllowedDomain : Entity
{
    [Key]
    public int DomainId { get; set; }

    public string Domain { get; set; }
}

這是我的Seed方法:

protected override void Seed(DbContext context)
{   
    var notAllowedDomainsList = new List<NotAllowedDomain>
    {
        new NotAllowedDomain {Domain = "test.com"},
        new NotAllowedDomain {Domain = "test1.com"},
        new NotAllowedDomain {Domain = "test2.co"}
    };

    notAllowedDomainsList.ForEach(x => context.NotAllowedDomains.AddOrUpdate(n => n.Domain, x));
}

在Add-Migration AddingNotAllowedDomains之后,我運行Update-Database並收到此錯誤:

Running Seed method.
System.InvalidOperationException: Saving or accepting changes failed because more than one entity of type 'Model.NotAllowedDomain' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.
   at System.Data.Entity.Core.Objects.ObjectStateManager.FixupKey(EntityEntry entry)
   at System.Data.Entity.Core.Objects.EntityEntry.AcceptChanges()
   at System.Data.Entity.Core.Objects.EntityEntry.ChangeObjectState(EntityState requestedState)
   at System.Data.Entity.Core.Objects.EntityEntry.ChangeState(EntityState state)
   at System.Data.Entity.Internal.StateEntryAdapter.ChangeState(EntityState state)
   at System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value)
   at System.Data.Entity.Infrastructure.DbEntityEntry.set_State(EntityState value)
   at Repository.Pattern.Ef6.DataContext.SyncObjectsStatePreCommit()
   at Repository.Pattern.Ef6.DataContext.SaveChanges()
   at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Saving or accepting changes failed because more than one entity of type 'Model.NotAllowedDomain' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.

有什么幫助嗎?

您是否具有NotAllowedDomainEntityTypeConfiguration類?

public class NotAllowedDomainConfiguration : EntityTypeConfiguration<NotAllowedDomain>
{
    public NotAllowedDomainConfiguration()
    {
        //Table
        ToTable("NotAllowedDomains");

        //Primary key
        HasKey(e => e.DomainId);

        //Properties
        Property(e => e.DomainId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(e => e.Domain).HasMaxLength(100).IsRequired();
    }
}

通過重寫OnModelCreating方法在DbContext類中引用此方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new NotAllowedDomainConfiguration());
    base.OnModelCreating(modelBuilder);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM