简体   繁体   中英

entity framework seed data issue

I use Asp.net Mvc, Entity Frameowrk on my project. My context class is:

public class SiteContext : DbContext, IDisposable
{
    public SiteContext() : base("name=SiteContext") { }

    public DbSet<SystemUsers> SystemUsers { get; set; }
    public DbSet<UserRoles> UserRoles { get; set; }
    public DbSet<Person> Person { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SiteContext>());
       Database.SetInitializer(new MigrateDatabaseToLatestVersion<SiteContext, Configration>());
    }
}

My configuration class for Migration is :

public class Configration : DbMigrationsConfiguration<SiteContext>
{
    public Configration()
    {
        AutomaticMigrationsEnabled = true; // also I changed this to false
        AutomaticMigrationDataLossAllowed = true; //also I changed this to false
    }

protected override void Seed(SiteContext context)
{

     new List<Person>
          {
             new Person {Id=1, Name="admin",SurName="admin",Email="admin@admin.com",IdentityNumber="12345678900"},
          }.ForEach(a => context.Person.AddOrUpdate(a));

        context.SaveChanges();
    }
}

I use AddorUpdate command for migration. Problem is in seed part. It doesn't add Person record once. It adds Person record every time. How can I solve this problem?

Try this:

context.Person.AddOrUpdate(p => new {p.Id}, <yourpersonobject>);
context.SaveChanges();

So it can take Id as the unique identifier key.

Or in your case:

new List<Person>
      {
         new Person {Id=1, Name="admin",SurName="admin",Email="admin@admin.com",IdentityNumber="12345678900"},
      }.ForEach(a => context.Person.AddOrUpdate(p => new {p.Id}, a));

Should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM