Robert
Robert

Reputation: 1638

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);
    }
}

Upvotes: 3

Views: 4491

Answers (1)

Pawel
Pawel

Reputation: 31620

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)

Upvotes: 7

Related Questions