Confusion about generation of database and seeding

1k Views Asked by At

I am using entity framework code first and also I have data seeding code

Now when I run my application my database gets generated but is not seeded with my dummy data. I have to run entity framework once more to get all data populated.

Any idea why and how to fix that so i do not have to run my app 2x to get database and data?

thnx

my context definition file is:

 public class Context : DbContext
    {
        public DbSet<Task> Tasks { get; set; }
        public DbSet<Agency> Agency { get; set; }

      protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
        base.OnModelCreating(modelBuilder);
     }
    }

And here is my seeding file

public class Configuration : DbMigrationsConfiguration<Context>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }

    protected override void Seed(Context context)
    {
        GenerateTasks(context);
        context.SaveChanges();
    }

    private static void GenerateTasks(Context context)
    {
        if (context.Task.Any()) return;
        context.Task.Add(new Task() { Name = "Received" });            
    }
}

And hook to create database is:

  Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
  var context = new Context();
  context.Database.Initialize(true);
2

There are 2 best solutions below

0
On BEST ANSWER

If your app is an ASP.NET one and is a seperate assembly from the data layer, then you can, instead of configuring the initialization like you did, configure it directly in the web.config. Maybe this is the reason for your problem.

So if it's an ASP.NET app, you can try the following:

(1)

Comment this out:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
var context = new Context();
context.Database.Initialize(true);

(2)

In web.config, insert this right at the end before the closing /configuration tag:

<entityFramework>
<contexts>
  <context type="**fully-qualified name of your context class**,
                 **assembly name of your context**">
    <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[**fully-qualified name of your context class**, **assembly name of your context**],
                               [**fully-qualified configuration type**, **assembly name of your context**, Version=1.0.0.0, Culture=neutral]], EntityFramework"/>
  </context>
</contexts>

where fully-qualified configuration type is the class with your migrations-configuration (something like [...]Context.Migrations.Configuration)

I use this configuration-approach for myself in my projects and it works well!

2
On

That's true. call context.Tasks.Find(1) and then it will hit the database. EF code-first uses this trick to postpone every thing. this way application's startup time seems much faster. (but actually it's not!)