1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, that was what I already tried but got "unrecognized database" or something (cant really remember). I did however fix the key length problem with MySql so maybe it had something to do with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.