A day with .Net

My day to day experince in .net

Seed database on application start EF code first

Posted by vivekcek on May 30, 2013

Create Your Context Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
 
namespace ContosoUniversity.Models
{
    public class SchoolContext : DbContext
    {
       
    }
}

Create a context initializer class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ContosoUniversity.Models;

namespace ContosoUniversity.DAL
{
    public class SchoolInitializer : DropCreateDatabaseIfModelChanges<SchoolContext>
    {
        protected override void Seed(SchoolContext context)
        {

        }
    }
}

Add this code under Application_Start(). Please remove this code in production.

Database.SetInitializer<SchoolContext>(new SchoolInitializer());
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s