Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

c# - Entity Framework code first, isn't creating the database

Here's an overview of how my solution looks:

enter image description here

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

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

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?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...