实体框架代码第一,不是创建数据库 [英] Entity Framework code first, isn't creating the database

查看:126
本文介绍了实体框架代码第一,不是创建数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的解决方案的概述:

Here's an overview of how my solution looks:

这是我的PizzaSoftwareData类:

Here's my PizzaSoftwareData class:

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博客的一个例子,你必须在应用程序开始时运行此代码才能创建/更新数据库模式。

According to an example on Scott Guthrie's blog, you have to run this code at the beginning of the application in order to create/update the database schema.

Database.SetInitializer<PizzaSoftwareData>(new CreateDatabaseIfNotExists<PizzaSoftwareData>());

我正在PizzaSoftware.UI中的Program.cs中运行一行代码。

I'm running that line of code from Program.cs in PizzaSoftware.UI.

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());
        }
    }
}

任何人都可以告诉我为什么数据库没有创建表?

Can anyone tell me why the database isn't having the tables created?

以下是我的App.config文件中的连接字符串:

Here's the connection string in my App.config file:

<?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>


推荐答案

当您需要访问数据库时,会执行初始化程序。如果要在应用程序启动时创建数据库,请使用:

Initializer is executed when you need to access the database. If you want to create database on application start either use:

context.Database.Initialize(true);

或不要使用初始化程序并调用:

Or don't use initializer and call:

context.Database.CreateIfNotExists();

这篇关于实体框架代码第一,不是创建数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆