Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to use custom database initializer

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!

like image 739
Dandry Avatar asked Apr 30 '16 09:04

Dandry


1 Answers

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.

like image 101
Hamid Pourjam Avatar answered Nov 05 '22 13:11

Hamid Pourjam