Mihai Bratulescu
Mihai Bratulescu

Reputation: 1945

Create database with data

I'm trying to create my database (code first) and I want to add some data in it when it's created.

public class InitializerWithData : CreateDatabaseIfNotExists<DatabaseContext>
        {
            protected override void Seed(DatabaseContext ctx)
            {
                GroupType gt = new GroupType() { Name = "RNC" };
                //save
                ctx.GroupType.Add(gt);
                ctx.SaveChanges();
            }
        }

        public DatabaseContext()
        {
            Database.SetInitializer<DatabaseContext>(new InitializerWithData());
            Database.CreateIfNotExists();
        }

As you can see I wrote my custom initializer but the code inside it is never fired though the database does get created.

So how do I solve this?

Upvotes: 1

Views: 31

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

When you call Database.CreateIfNotExists(), it doesn't trigger the InitializeDatabase of the initializer. Basically it has separated implementation than the initializer.

If you want the Seed method to be fired. You need to execute a code that causes EF to send a query to the database.

First remove this line.

Database.CreateIfNotExists();

Then just execute a query, the least you could have is something like.

using(var db = new DatabaseContext())
{
    db.Set<GroupType>().Any();
}

This code will create the database if it doesn't exist and execute the Seed method.

Upvotes: 1

Related Questions