我有以下代码:
public DataInitializer() {
Database.SetInitializer<DataContext>(null);
try {
using (var context = new DataContext()) {
if (!context.Database.Exists())
{
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
}
catch (Exception ex) {
throw new InvalidOperationException("The Data database could not be initialized", ex);
}
}
和
public class DataContext : DbContext
{
public DataContext() : base("xxdata") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<Application> Applications { get; set; }
}
当我单步执行代码时会执行代码,但似乎没有创建数据库文件(SQL Server Express)。
有什么明显的东西我做错了吗?
答案 0 :(得分:1)
创建一个继承的类,如下所示;
public class DataContextInitializer : DropCreateDatabaseAlways<DataContext>
{
protected override void Seed(DataContext context)
{
//Seed data if you want
}
}
并将其添加到您的Global.asax
protected void Application_Start()
{
//Add your database initializer code
Database.SetInitializer(new DataContextInitializer());
}