如何通过 Code-First Entity Framework 方法在 SQL Server 2017 而不是 LocalDB 或 SQL Express 上创建数据库?

How to create database on SQL Server 2017 instead of LocalDB or SQL Express via Code-First Entity Framework approach?

其实标题已经概括了我的全部问题。我正在使用 Visual Studio 2017 和 Entity Framework 6。在我的 MVC 应用程序中,当我遵循 code-first 方法时,在默认设置下,我只获得了 LocalDB 或 SQL 的选项Server Express 在 SQL Server Object Explorer 中使用。我可以使用 SQL Express 查看我的模型的相应表格。

但是,我想使用我的 SQL Server 2017。我想我必须在连接字符串中指定我想要的数据库,但我不知道如何使用 Entity Framework 6.

您可以只打开您的项目 web.config 文件或 app.config 文件,然后更新您的 entity framework 连接字符串以引用您需要的 SQL 服务器实例如下所示:

 <add name="DefaultConnection" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=YourServerInstance;Initial Catalog=YourDB;Persist Security Info=True;User ID=sa;Password=123456;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

通过检查您的上下文 class 以检查它引用的连接字符串键名,确保您正在编辑正确的连接字符串:

public YourContext(bool lasyLoadingEnabled) : base("DefaultConnection")
{
    Database.SetInitializer<NimasContext>(null);
    this.Configuration.LazyLoadingEnabled = lasyLoadingEnabled;
    this.Configuration.ProxyCreationEnabled = false; ;
}

你可以关注这个link: https://msdn.microsoft.com/en-us/library/jj556606(v=vs.113).aspx