Techbubbles

Seeding a Database in Entity Framework

The code-first approach of Entity Framework creates the database in LocalDB instance of SQL Server Express. The Entity Framework uses the model’s property names and data types to create the tables.Entity Framework uses EdmMetadata table to synchronize model classes with the database schema. To keep the database in sync with the model you need to re-create an existing database using Entity Framework. EF allows you to create the database every time when application starts or only create when it detects a change in the model.

Database Initializers

You have to call the static SetInitializer method of EF’s database class which is in System.Data.Entity namespace. Example as below

 protected void Application_Start()
        {

            Database.SetInitializer(new DropCreateDatabaseAlways<ProductDBContext>());

            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

You can use any one of the two database initializers DropCreateDatabaseAlways and DropCreateDatabaseModelChanges

After creating the database, you may want to add some data to the tables. Now you can derive a class named DropCreateDatabaseAlways and override the seed method. In seed method you can create some dummy records for the application using the below code

public class ProductDbInitializer
         : DropCreateDatabaseAlways<ProductDBContext>
    {
        protected override void Seed(ProductDBContext context)
        {
            context.Products.Add(new Product { ProductName="Apple",
                                               color = "White",
                                                Price = 399,
                                                 ProductId=100
                                               });
            
            base.Seed(context);
        }
    }

Now change the code in Application_Start to register the initializer as below

        protected void Application_Start()
        {

            Database.SetInitializer(new ProductDbInitializer());

            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

Related Posts:

%d bloggers like this: