I am building a simple MVC application for managing a library. For development purposes, I would like the EF to drop and recreate the database everytime the model changes, as well as filling it with some sample data. At this moment I struggle at getting the initializer to work. The Initializer class looks like this:
public class LibraryInitializer : DropCreateDatabaseIfModelChanges<LibraryContext>
{
protected override void Seed(LibraryContext context)
{
// sample data to be writted to the DB
}
}
And the context class looks like this:
public class LibraryContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Book> Books { get; set; }
public LibraryContext()
{
Database.SetInitializer<LibraryContext>(new LibraryInitializer());
}
}
At this moment I get the following error:
Member 'Database.SetInitializer(IDatabaseInitializer)' cannot be accessed with an instance reference; qualify it with a type name instead
Based on many guides available on the Web, this is the way to use the initializer, but I have no idea why this error occurs. Any help would be greatly appraciated. Thank you!
In C#
you can't access static
members from instances. You must access static
members using the name of the type. Use full type name.
System.Data.Entity.Database.SetInitializer<LibraryContext>(new LibraryInitializer());
DbContext
has a Database
property which is an instance of System.Data.Entity.Database
class. When you write Database
in your DbContext
it points to that instance and since you can not access static methods from instances you get the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With