unable to use custom database initializer

a 夏天 提交于 2020-03-21 19:30:35

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/36953401/unable-to-use-custom-database-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!