Entity Framework Code First AddOrUpdate method insert Duplicate values

后端 未结 13 1148
清酒与你
清酒与你 2020-12-01 08:52

I have simple entity:

public class Hall
{
    [Key]
    public int Id {get; set;}

    public string Name [get; set;}
}

Then in the S

相关标签:
13条回答
  • 2020-12-01 09:36

    I know this is an old question, but the right answer is that if you are setting the id # yourself and you want to use AddOrUpdate then you need to tell EF/SQL that you don't want it to generate the ID #.

    modelBuilder.Entity<MyClass>().Property(p => p.Id)
        .HasDatabaseGeneratedOption(System.ComponentModel
        .DataAnnotations.Schema.DatabaseGeneratedOption.None); 
    

    The down side to this is that when you insert a new item you need to set it's Id, so if this is done dynamically at runtime (instead of from seed data) then you will need to calculate out the next Id. Context.MyClasses.Max(c=>c.Id) + 1 works well.

    0 讨论(0)
  • 2020-12-01 09:36

    Just to Ciaren's answer, the below code of resetting the context on ModelCreating, helped me resolve similar issues. Make sure change "ApplicationContext" to your DbContext name.

    public class ApplicationContext : DbContext, IDbContext
        {
            public ApplicationContext() : base("ApplicationContext")
            {
                 
            }
    
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
                Database.SetInitializer<ApplicationContext>(null);
                base.OnModelCreating(modelBuilder);
            }
         }

    0 讨论(0)
  • 2020-12-01 09:37

    This code works:

    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }
    
    protected override void Seed(HallContext context)
    {
        context.Halls.AddOrUpdate(
            h => h.Id,
            new Hall
            {
                Id = 1,
                Name = "Hall 1"
            },
            new Hall
            {
                Id = 2,
                Name = "Hall 2"
            });
    
        context.SaveChanges();
    }
    
    0 讨论(0)
  • 2020-12-01 09:37

    If object(hall)'s id is 0, it is a insertion. I think you need to double check the id field of your hall objects

    0 讨论(0)
  • 2020-12-01 09:41

    You could have also done this:

     context.Halls.AddOrUpdate(new Hall[]{hall1,hall2, hall3});
    
    0 讨论(0)
  • 2020-12-01 09:42

    I think it's likely that you need to back out existing database migrations (i.e. start your database from scratch) with something like Update-Database TargetMigration:0 followed by Update-Database.

    As it is, you're not dropping the existing table or values, you're just add/updating those values. That needs to happen in order to get your desired result.

    0 讨论(0)
提交回复
热议问题