0

我有以下代码:

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)。

有什么明显的我做错了吗?

4

1 回答 1

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());
}
于 2013-03-10T08:07:24.000 回答