无法使用自定义数据库初始化程序 [英] unable to use custom database initializer
问题描述
我正在构建一个用于管理库的简单MVC应用程序。出于开发目的,我希望EF在每次模型更改时删除并重新创建数据库,并用一些示例数据填充它。目前,我在努力使初始化程序起作用。 Initializer类如下所示:
公共类LibraryInitializer:DropCreateDatabaseIfModelChanges< LibraryContext>
{
受保护的覆盖无效void Seed(LibraryContext context)
{
//要写入数据库的示例数据
}
}
上下文类如下:
公共类LibraryContext:DbContext
{
public DbSet< User>用户{get;组; }
public DbSet< Book>书{组; }
public LibraryContext()
{
Database.SetInitializer< LibraryContext>(new LibraryInitializer());
}
}
此刻,我得到以下错误:
成员'Database.SetInitializer(IDatabaseInitializer)'不能通过实例引用进行访问;用类型名称代替它
基于网络上提供的许多指南,这是使用初始化程序的方法,但是我不知道为什么会发生此错误。
任何帮助将得到极大的赞赏。
谢谢!
在 C#
中,您可以'从实例访问静态
成员。您必须使用类型名称访问 static
成员。使用完整的类型名称。
DbContext
的 Database
属性,它是 System.Data.Entity.Database
类的实例。当您在 DbContext
中写入数据库
时,它指向该实例,并且由于无法从实例访问静态方法,因此错误。
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.
这篇关于无法使用自定义数据库初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!