Reputation: 85
I try learning something in Asp net Mvc, but I have a trouble. I wish my data were not duplicated when I start the program every time. I thought that it will be working fine and my data will create while first run. Why does not work it?
Store Context:
namespace StoreProject.DAL
{
using StoreProject.Models;
using System;
using System.Data.Entity;
using System.Linq;
public class StoreContext : DbContext
{
public StoreContext()
: base("name=StoreDb")
{
}
static StoreContext()
{
Database.SetInitializer<StoreContext>(new StoreInitializer());
}
public virtual DbSet<Product> Products { get; set; }
}
}
Storeinitializer:
namespace StoreProject.DAL
{
public class StoreInitializer : MigrateDatabaseToLatestVersion<StoreContext, Configuration>
{
public static void SeedStoreData(StoreContext context)
{
var products = new List<Product>
{
new Product(){Name = "Chockolate1",Price = 2.20f, Country = "Russia"},
new Product(){Name = "Chockolate2", Price=3.30f, Country = "Poland"},
};
products.ForEach(a => context.Products.AddOrUpdate(a));
context.SaveChanges();
}
}
}
Configuration in Migrations folder
using System.Collections.Generic;
using StoreProject.DAL;
using StoreProject.Models;
namespace StoreProject.Migrations
{
public sealed class Configuration : DbMigrationsConfiguration<StoreProject.DAL.StoreContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "StoreProject.DAL.StoreContext";
}
protected override void Seed(StoreProject.DAL.StoreContext context)
{
StoreInitializer.SeedStoreData(context);
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
}
}
}
Upvotes: 0
Views: 254
Reputation: 4430
You are not giving it a key/key combo to compare against so everything you pass in is an Add operation as far as it is concerned.
products.ForEach(product => context.Products.AddOrUpdate(p => new {p.Name, p.Country}, product));
Upvotes: 2