Mert Akcakaya
Mert Akcakaya

Reputation: 3129

Seeding data in custom Db Initializer won't work / EF, Code First

I am trying to seed some data using custom database initializers, but can't get it to work. I tried adding some configurations to appConfig file but that didn't work either.

It is a WPF application and I don't want to reference my EntityLibrary. I want to seed data using context's constructor. What's wrong with it?

Edit: The problem is no data gets populated. When debugging I see the context's constructor SetInitiazlier function is called but overridden Seed method never gets called, in fact debugger never enters the Seed method.

At the same time XAML parser gives an error complaining about the TContext type paramter of DropCreateDatabaseIfModelChanges. I can't give the exact error since I don't have the code at home.

This is my custom initializer:

public class DbInitializer : DropCreateDatabaseIfModelChanges<DemirbaşContext>
    {
        protected override void Seed(DemirbaşContext context)
        {
            Kullanıcı kullanıcı = new Kullanıcı
            {
                Ad = "Mert",
                Soyad = "Mert",
                KullanıcıAdı = "admin",
                Şifre = "password",
                Email = "[email protected]"
            };

            context.Kullanıcılar.Add(kullanıcı);
            context.SaveChanges();

            base.Seed(context);
        }
    }

This is my context constructor:

public DemirbaşContext():base("Demirbaş")
    {
        Database.SetInitializer<DemirbaşContext>(new DbInitializer());
    }

EDIT 1: Here is my current code, but still it does not seed the data. Can you see what's wrong?

Initializer:

public class DbInitializer : DropCreateDatabaseIfModelChanges<DemirbaşContext>
{
    protected override void Seed(DemirbaşContext context)
    {
        Kullanıcı kullanıcı = new Kullanıcı
        {
            Ad = "Mert",
            Soyad = "Mert",
            KullanıcıAdı = "admin",
            Şifre = "password",
            Email = "[email protected]"
        };

        context.Kullanıcılar.Add(kullanıcı);
        context.SaveChanges();

    }
}

Application Startup:

public partial class App : Application
    {
        public App()
        {
            // Seed data, remove after getting seeding in custom db initiazlier to work
            DemirbaşContext context = new DemirbaşContext();
            DbInitializer initializer = new DbInitializer();
            Database.SetInitializer<DemirbaşContext>(initializer);
            context.Database.Initialize(false);
        }
    }

Upvotes: 1

Views: 6190

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

Move your initialization code to your application startup. It doesn't belong to context's constructor and force initialization manually:

Database.SetInitializer<DemirbaşContext>(new DbInitializer());
context.Database.Initialize(false);

Upvotes: 4

Related Questions