Error when running Seed method

Apr 2, 2014 at 4:44 PM
I was trying to run the update-database command to insert some initial data in my database and I got and error. Here is my entity:
[Table("NotAllowedDomain")]
public class NotAllowedDomain : Entity
{
    [Key]
    public int DomainId { get; set; }

    public string Domain { get; set; }
}
and here is my Seed method:
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));
}
After the Add-Migration AddingNotAllowedDomains, I ran Update-Database and got this error:
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(IEnumerable1 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.
Any Help?
Coordinator
Apr 7, 2014 at 1:04 AM
This is an Entity Framework Code-First issue, unfortunately our experience with CodeFirst is with around Entity Framework PowerTools (Reverse Engineer Code-First) http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d.
Marked as answer by lelong37 on 4/6/2014 at 6:04 PM
Apr 9, 2014 at 1:30 PM
Edited Apr 9, 2014 at 1:31 PM
I think the issue is related with the AddOrUpdate method, because I was checking a lil bit the samples and the way the insertions and updates are made in the framework and you have to specify the ObjectState first in order for the repository to knows the state of the entity:
public Country Create(Country country)
        {
            country.ObjectState = ObjectState.Added;
            _unitOfWork.Repository<Country>().Insert(country);
            return country;
        }
and in my seed code:
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));
}
I am using the AddOrUpdate method but the context doesn't know the state of my entity. And not sure if that is a true statement but I think that could be the issue.
Coordinator
Apr 9, 2014 at 4:54 PM
ddieppa,

Yes, the DbContext in the Framework requires that you set the ObjectState for every entity that passes through it.
May 26, 2014 at 5:04 AM
I had the same issue with my Seed method. I should have checked here first, but finally came to the same conclusion as Long did, that you need to set
ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added.
I also found that I had to specifically set each entity's Id property to something unique.

e.g
``` ` public partial class ExampleContext : DataContext
{
    public ExampleContext()
        : base("name=ExampleContext")        {
    }

    static ExampleContext()
    {
        Database.SetInitializer<ExampleContext>(new CreditorsDbInitializer());
    }
...
public class CreditorsDbInitializer : DropCreateDatabaseAlways<ExampleContext>
{
    protected override void Seed(ExampleContext context)
    {
        ExampleDBInitializer.Seed(context);
        base.Seed(context);
    }
}

public static class ExampleDBInitializer
{
    public static void Seed(Example.Entities.ExampleContext context)
    {
        var ExampleEntitys = new List<ExampleEntity>
        {
            new ExampleEntity {ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added, ExampleEntityId = 1},
            new ExampleEntity {ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added, ExampleEntityId = 2},
        };
        ExampleEntitys.ForEach(s => System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate(context.ExampleEntitys, u => u.ExampleEntityId, s));
        context.SaveChanges();
...
``