Reputation: 539
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="[email protected]",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?
Upvotes: 0
Views: 651
Reputation: 2874
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="[email protected]",IdentityNumber="12345678900"},
}.ForEach(a => context.Person.AddOrUpdate(p => new {p.Id}, a));
Should work
Upvotes: 1