EF 中的代码优先不会创建数据库

code first in EF doesn't create database

如您所见,我的解决方案中有 2 个项目:

我想先使用代码来创建我的数据库,所以我创建模型的代码是:

   namespace CMSDataLayer
{
   public class CMSDataContext : DbContext
    {
        public CMSDataContext()
      : base("DefaultConnection")
    {
      this.Configuration.LazyLoadingEnabled = false;
      this.Configuration.ProxyCreationEnabled = false;

      Database.SetInitializer(
        new MigrateDatabaseToLatestVersion<CMSDataContext, CMSMigrationsConfiguration>()
        );
    }
        public DbSet<table1> Topics { get; set; }
    }
}

 public class CMSMigrationsConfiguration : DbMigrationsConfiguration<CMSDataContext>
    {

        public CMSMigrationsConfiguration()
        {
            this.AutomaticMigrationDataLossAllowed = true;
            this.AutomaticMigrationsEnabled = true;
        }

    }
    }

我将连接字符串添加到 MVC 项目 webconfig

在 运行 之后,数据库未创建。我在 CMSDataContext class 中放置了一个断点,但断点从未 called.why ?

我第一次接触 EF 代码。

此致

据我所知,它不会在使用之前创建数据库。 尝试将一个实体添加到数据库中,然后查看它是否会创建它。

如果你想添加一些虚拟数据,你可以使用播种功能: seeding tutorial

在您的项目中,您没有手动建立任何数据库连接,这里是如何显示的:

View -> Server Explorer Right click on Data Connections and select Add Connection…
如果您在需要 select Microsoft SQL 服务器作为数据源之前没有从服务器资源管理器连接到数据库

Here是一篇解释如何添加EF的文章