How can I get my database for seed using Entity Framework CodeFirst?

The database is created successfully (like tables), but not seeded. I spent several hours and read many articles, but could not get them. Any suggestions?

On the other hand, is it possible to call the initializer without reference to my DatabaseContext on the client?

I included all the relevant code that I could think of. If anything else is helpful, please let me know.

Things I tried:

  • I deleted the connection string (since it defaults to sqlexpress, only the name is changed)
  • I changed DropCreateDatabaseIfModelChanges to DropCreateDatabaseAlways, all the same.

Edit: It is really strange that this worked once, but I have no idea how and why it broke again. I assume connection strings, but who knows.

DatabaseInitializer.cs

public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<DatabaseContext> { protected override void Seed(DatabaseContext context) { // Seeding data here context.SaveChanges(); } } 

DatabaseContext.cs

 public class DatabaseContext : DbContext { protected override void OnModelCreating(DbModelBuilder mb) { // Random mapping code } public DbSet<Entity1> Entities1 { get; set; } public DbSet<Entity2> Entities2 { get; set; } } 

Global.asax.cs - Application_Start ()

 protected void Application_Start() { Database.SetInitializer<DatabaseContext>(new DatabaseInitializer()); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } 

Web.config client

 <connectionStrings> <add name="DatabaseContext" connectionString="data source=.\SQLEXPRESS;Database=Database;Integrated Security=SSPI;" providerName="System.Data.SqlClient" /> </connectionStrings> 

DECISION

For documentation, I shared my solution here. In any case, moving all the comments would be a pain. In the end, I had DatabaseInitializer and DatabaseContext in separate classes. I do not understand, although these tiny changes corrected him, but here it is.

DatabaseInitializer.cs

 public class DatabaseInitializer : CreateDatabaseIfNotExists<DatabaseContext> { protected override void Seed(DatabaseContext context) { // Seed code here } } 

DatabaseContext.cs

 public class DatabaseContext : DbContext { public DatabaseContext() : base("MyDatabase") { } protected override void OnModelCreating(DbModelBuilder mb) { // Code here } public DbSet<Entity> Entities { get; set; } // Other DbSets } 

Global.asax.cs - Application_Start ()

 protected void Application_Start() { Database.SetInitializer(new DatabaseInitializer()); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } 
+62
entity framework asp.net-mvc-3 entity-framework code-first
Jun 10 2018-11-18T00:
source share
12 answers

This is what all my DbContext classes look like, and they seeds are just fine:

 public class MyDbContext : DbContext { public DbSet<MyClass> MyClasses { get; set; } protected override void OnModelCreating (DbModelBuilder modelBuilder) { base.OnModelCreating (modelBuilder); modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention> (); // Add any configuration or mapping stuff here } public void Seed (MyDbContext Context) { #if DEBUG // Create my debug (testing) objects here var TestMyClass = new MyClass () { ... }; Context.MyClasses.Add (TestMyClass); #endif // Normal seeding goes here Context.SaveChanges (); } public class DropCreateIfChangeInitializer : DropCreateDatabaseIfModelChanges<MyDbContext> { protected override void Seed (MyDbContext context) { context.Seed (context); base.Seed (context); } } public class CreateInitializer : CreateDatabaseIfNotExists<MyDbContext> { protected override void Seed (MyDbContext context) { context.Seed (context); base.Seed (context); } } static MyDbContext () { #if DEBUG Database.SetInitializer<MyDbContext> (new DropCreateIfChangeInitializer ()); #else Database.SetInitializer<MyDbContext> (new CreateInitializer ()); #endif } } 

I used this template several times and it worked out very well for me.

+36
Jun 13 2018-11-17T00:
source share

My Seed method was not called even with the correct call to Database.SetInitializer in Application_Start ... The reason for this was very simple: the initializer cannot be called at all if you do not already have code that uses the database context .

+10
Feb 11 '12 at 17:15
source share

This is my sad little tale.

First, lessons learned:

  • The seed method will not be called until the context is used.
  • Global.asax.cs will not hit a breakpoint the first time bc is started, which it starts before the debugger is attached. To get to the breakpoint on Global.asax.cs, you can add some space in Web.config and hit the page; then he will get hit.
  • If there is a VS connection to dB, no seeding will occur. The application will display an error.

So, to avoid sadness:

  • Disconnect the VS connection.
  • Switch the base class DropCreateDatabaseAlways at a time.
  • Click a page using context.

Now sadness:

  • My Global.asax.cs file had its own Initializer class. I had a breakpoint on my Initializer Seed method; I started the application and the method never hit. :(
  • I specify a breakpoint in a call to Database.SetInitializer in Application_Start. It never came across. :(
  • I realized that I have no db schema changes, so I changed DropCreateDatabaseIfModelChanges to DropCreateDatabaseAlways. Nothing yet.: (
  • Finally, I went to a page that uses context, and it worked.: /
+9
Nov 22
source share

You can call update-database to manually run the seed method inside the Configuration class. This requires enable-migrations .

 PM> update-database Specify the '-Verbose' flag to view the SQL statements being applied to the target database. No pending code-based migrations. Running Seed method. 



 internal sealed class Configuration : DbMigrationsConfiguration<ProjectManager.Data.Database.ProjectDb> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(ProjectManager.Data.Database.ProjectDb context) { context.Status.AddOrUpdate( new Status() { Id = 1, Text = "New" }, new Status() { Id = 2, Text = "Working" }, new Status() { Id = 3, Text = "Completed" }, new Status() { Id = 4, Text = "Skipped" } ); } } 
+3
Apr 15 '13 at 16:45
source share

The following change has changed in the Global.asax file:

Old code:

  protected void Application_Start() { Database.SetInitializer<mycontextclassname>(new DropCreateDatabaseAlways<mycontextclassname>()); ... } 

New code:

  protected void Application_Start() { Database.SetInitializer<mycontextclassname>(new DropCreateDatabaseAlways<mycontextclassname>()); Database.SetInitializer(new Initializer()); ... } 
+2
Jun 13 2018-12-12T00:
source share

It was also difficult for me to get Seed () to call. And I really appreciate all the useful suggestions above, and I was lucky with DropCreateDatabaseAlways ... but not ALWAYS !!

Most recently, I added the following line of code to the constructor of my repository:

  public CatalogRepository() { _formCatalog.FormDescriptors.GetType(); } 

It was enough to call the Seed () call. If you tried everything above this answer and still have no luck, try it. Good luck with that a lot of time.

+1
Dec 28
source share

The seed event in your example will only fire once when you use DropCreateDatabaseIfModelChanges, you can change this to DropCreateDatabaseAlways, I think, and it should fire a seed event every time.

Edit

This is my DataContext

 public WebContext() { DbDatabase.SetInitializer(new DropCreateDatabaseIfModelChanges<WebContext>()); } 
0
Jun 10 2018-11-11T00:
source share

This happened to me when I discovered Code First features. This situation often arises when you first used Code First to create your database without any initialization strategy.

If you decide to do this later, implementing a strategy based on DropCreateDatabaseIfModelChanges , but without changing the model, then your Seed method will not be called, since database generation and your strategy will be applied only the next time you change your model.

If this happens to you, try changing your model a bit to test this hypothesis, and I'm sure your database will be full;)

I don’t have a solution yet, except to use a strategy that always generates a database, but I'm really not sure that you put the initialization strategy in your DbContext, since this class will be used in you although the initialization strategy seems to be in mainly used for the free development of the environment.

0
Jan 05 '12 at 12:18
source share

I just ran into this problem. I removed the "connectionstrings" section from the Web.config file and the application is currently running - without the connectionstrings section! I add the section back and the database is not sown again. This is not the right solution, but I'm just adding a data item here that could potentially solve the problem.

Fortunately, this is just a small β€œdropped” application that I will soon drop ...

0
Jun 16 2018-12-12T00:
source share

Updated to note that this answer is incorrect! The reason that my DB does not receive the seed remains a mystery (but it was not the absence of a default constructor call, as @JaredReisinger noted)

I understand this question is a little old, but I ended up here so that someone else could. Here is my tappence:

My database was created perfectly, but it was not sowing, even if I deleted the database and started using DropDatabaseInitialiser again.

After reading the above code, I noticed that my context constructor was this

 public MyApp_Context() { // some code } 

whereas the above example will be the following for my installation

 public MyApp_Context() : base("name=MyApp_Context") { // some code } 

Yup, I did not call the constructor of the base object! I would not expect everyone except sowing to work on this specimen, but this seems to be a (repeatable) case.

NB, I really do not need to specify the context name in the call to the base constructor; I just wrote it like this because I copied the solution format above. So my code is now, and sowing works when the database is initially created.

 public MyApp_Context() : base() { // some code } 
0
Jul 09 '13 at 15:33
source share

Carefully ensure that you have not declared your context variable more than once. If you declare it again after sowing, the seed will be overwritten.

0
Jan 05 '16 at 20:57
source share

I had the same problem, and after changing the Global.asax and Intializer it worked. I hope this works for those who still have problems sowing data.

New code in Global.asax:

  protected void Application_Start() { Database.SetInitializer<mycontextclassname>(new DropCreateDatabaseAlways<mycontextclassname>()); Database.SetInitializer(new Initializer()); ... } 

code for Intializer file:

 public class Initializer : System.Data.Entity.DropCreateDatabaseAlways<Context> 
0
Aug 21 '16 at 11:23
source share



All Articles