How to seed data when using Model First approach?

不问归期 提交于 2019-12-03 00:09:28

You can have something like this:

public class MySeedData : DropCreateDatabaseIfModelChanges<YourDataBaseContextClass>
{
    protected override void Seed(YourDataBaseContextClass context)
    {  
       // Create objects here and add them to your context DBSets...

    }
}

public class YourDataBaseContextClass : DbContext
{


}

Then, within Application_Start() you call:

Database.SetInitializer(new MySeedData());

In your case, you could try creating DbSets (using your model first classes) manually and try to plug it using the code above. It's kind of a mix of Model First + Code First.

public class FourthCoffeeWebContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

Adding to this: CreateDatabaseIfNotExists<(Of <(<'TContext>)>)>

Model first is significantly different from Code First as you actually generate the database from the model as you're working on it. You get the SQL to create the database and run it manually, therefore I found it logical to keep next to this a 2nd SQL script with my seed data.

If I make changes to the model, The SQL script is updated and I of course need to review my seed SQL script (which is conveniently located right next to my Database creation script) I just run 1 after the other.

This approach has been working fine so far and doesn't create the confusion of 'where is this data loader and how does it identify an empty database'. (I can also include both these SQL scripts in my Setup project for my custom action to create the database with seed data.)

I use a Seeding Controller similar to the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyProject.Models;

namespace MyProject.Controllers
{
    public class SeedController : Controller
    {
        public string Index()
        {
            ContactDBContext db = new Models.ContactDBContext();

            Person person = new Person();
            person.FullName = "Mr Test";
            person.Notes = "It's me!";
            db.People.Add(person);
            db.SaveChanges();
            return "Seeding complete.";
        }
    }
}

Then after you have recreated your database from the Model Entity diagram simply navigate to the "/Seed" url of your website and it will repopulate with your seed data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!