Simone
Simone

Reputation: 2430

Entity Framework Code First Seed database

I am using E.F. with Code First approach... Now I have to fill the database with some data... but I cannot do it easily... Simething is not clear... I have googled but every solution I have found suppose I must create a custom Initilization... but I do not want to create a custom Initialization..

What I need is a method the everytime I launch some tests DROP the database, RE-CREATE it and fill it with some data.

What I have tried to do is:

public PublicAreaContext()
    : base("PublicAreaContext")
{
    Database.SetInitializer<PublicAreaContext>(new DropCreateDatabaseAlways<PublicAreaContext>());
}

Then I have tried to impement the Seed method inside the Configuration class. So:

internal sealed class Configuration : DbMigrationsConfiguration<PublicAreaContext>
{
    protected override void Seed(PublicAreaContext context)
    {
        ...
    }
}

But when I try to debug I never go in the seed method... I go in constructor of the Configuration class, but not in the seed... why?

Thanx for your help

Upvotes: 2

Views: 13281

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

You are confusing seed methods. There is one for initializers that you can use when your database is created and there is one for migrations. See http://blog.oneunicorn.com/2013/05/28/database-initializer-and-migrations-seed-methods/

Since you are using DropCreateDatabaseAlways, migrations won't run, so do something like this:

public static class MyDatabase
{
    public static void Initialize()
    {
        Database.SetInitializer(new MyInitializer());
    }
}

public class MyInitializer : DropCreateDatabaseAlways<PublicAreaContext>
{
    protected override void Seed(PublicAreaContext context)
    {
        base.Seed(context);
        context.Roles.Add(new Role
        {
            ID = 1,
            Name = "User",
        });
        context.Roles.Add(new Role
        {
            ID = 2,
            Name = "Admin",
        });
        context.SaveChanges();
    }
}

Other examples: http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm

http://www.techbubbles.com/aspnet/seeding-a-database-in-entity-framework/

Upvotes: 6

Related Questions