[英]entity framework seed data issue
我在項目上使用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命令進行遷移。 問題出在種子部分。 它不會一次添加“個人”記錄。 每次添加人員記錄。 我怎么解決這個問題?
嘗試這個:
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));
應該管用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.