以下是我的解决方案的概述:
这是我的PizzaSoftwareData类:
namespace PizzaSoftware.Data
{
public class PizzaSoftwareData : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<User> Users { get; set; }
}
}
根据Scott Guthrie博客上的一个示例,您必须在应用程序的开头运行此代码才能创建/更新数据库架构。
Database.SetInitializer<PizzaSoftwareData>(new CreateDatabaseIfNotExists<PizzaSoftwareData>());
我在PizzaSoftware.UI中的Program.cs中运行那行代码。
namespace PizzaSoftware.UI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Database.SetInitializer<PizzaSoftwareData>(new CreateDatabaseIfNotExists<PizzaSoftwareData>());
Application.Run(new LoginForm());
}
}
}
有人能告诉我为什么数据库没有创建表吗?
这是我的App.config文件中的连接字符串:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="PizzaSoftwareData"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SaharaPizza;Integrated Security=True;Pooling=False"
providerName="System.Data.Sql" />
</connectionStrings>
</configuration>
答案 0 :(得分:30)
初始化程序在您需要访问数据库时执行。如果要在应用程序启动时创建数据库,请使用:
context.Database.Initialize(true);
或者不要使用初始化程序并致电:
context.Database.CreateIfNotExists();
答案 1 :(得分:4)
而不是将此代码放入main方法:
Database.SetInitializer<PizzaSoftwareData>(new CreateDatabaseIfNotExists<PizzaSoftwareData>());
将它放入DBContext:
namespace PizzaSoftware.Data
{
public class PizzaSoftwareData : DbContext
{
public PizzaSoftwareData()
: base("name=PizzaSoftwareData")
{
Database.SetInitializer<PizzaSoftwareData>(new CreateDatabaseIfNotExists<PizzaSoftwareData>());
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<User> Users { get; set; }
}
}