0

我在我的项目中使用 Asp.net Mvc,Entity Frameowrk。我的上下文类是:

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>());
    }
}

我的迁移配置类是:

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();
    }
}

我使用 AddorUpdate 命令进行迁移。问题出在种子部分。它不会一次添加人员记录。它每次都添加人员记录。我怎么解决这个问题?

4

1 回答 1

1

尝试这个:

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

所以它可以将Id作为唯一标识符键。

或者在你的情况下:

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));

应该管用

于 2013-07-30T13:06:13.783 回答