Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First: Initializing a Database using Console Application

I'm trying to run initialization code and it is not running. Here's what I have in the main method

    static void Main(string[] args)
    {
        Database.SetInitializer<Context>(new RecipesSeedData());

    }

Am I supposed to put something else in main to get it to run the below code ? When I step through the code in the debugger it's not even getting to the initialization code which makes me feel like I'm missing something important.

public class RecipesSeedData : DropCreateDatabaseAlways<Context>
{
    protected override void Seed(Context context)
    {
        var mt = new MenuType {MenuTypeId = 1};

        context.MenuTypes.Add(mt);

        base.Seed(context);
    }
}
like image 670
Robert Avatar asked Aug 31 '26 21:08

Robert


1 Answers

You just told EF that when initializing the database it needs to use your initializer but you did not tell it to actually initialize the database. The database will be initialized when you do some operation on the DbContext. Here is a great post that exactly describes what's happening under the hood: http://blog.oneunicorn.com/2011/04/15/code-first-inside-dbcontext-initialization/ (including details about DbInitializers)

like image 80
Pawel Avatar answered Sep 05 '26 03:09

Pawel