Cześć tworze sobie stronę w ASP.Net Mvc, ale mam problem z inicjalizacją danych. Chcę by dane były wprowadzone tylko przy pierwszym uruchomieniu programu. Myślałem, że dobrze to zrobiłem,ale te same dane są dodawane przy każdym uruchomieniu. Bazę zrobiłem w CodeFirst.
Tutaj mój Context:
namespace StoreProject.DAL
{
using StoreProject.Models;
using System;
using System.Data.Entity;
using System.Linq;
public class StoreContext : DbContext
{
// Your context has been configured to use a 'StoreContext' connection string from your application's
// configuration file (App.config or Web.config). By default, this connection string targets the
// 'StoreProject.DAL.StoreContext' database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the 'StoreContext'
// connection string in the application configuration file.
public StoreContext()
: base("name=StoreDb")
{
}
static StoreContext()
{
Database.SetInitializer<StoreContext>(new StoreInitializer());
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
public virtual DbSet<Product> Products { get; set; }
}
//public class MyEntity
//{
// public int Id { get; set; }
// public string Name { get; set; }
//}
}
Initializer:
using StoreProject.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Web;
using StoreProject.Migrations;
namespace StoreProject.DAL
{
public class StoreInitializer : MigrateDatabaseToLatestVersion<StoreContext, Configuration>
{
public static void SeedStoreData(StoreContext context)
{
var products = new List<Product>
{
new Product(){Name = "Czekolada biała",Price = 2.20f, Country = "Madagaskar"},
new Product(){Name = "CzekoladaCzarna", Price=3.30f, Country = "Belgia"}
};
products.ForEach(a => context.Products.AddOrUpdate(a));
context.SaveChanges();
}
}
}
Configuration w Migrations:
using StoreProject.DAL;
namespace StoreProject.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
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.
}
}
}