您的位置:首页 > 编程语言 > ASP

在ASP.NET中使用SQL Server作为数据库,DB First方式使用EF(EntityFramework)进行开发和部署时的connectionString

2017-04-07 18:31 836 查看
这个问题困扰了我一个下午,项目采用的是VS2015,DB使用的是SQL Server2014.

在项目中生成EF时(*.edmx),因为是本机数据库,当时选择的是windows的连接方式,这样生成了connectionString在Web.Config中。

但是当把项目发布到本地后,发现DB连接不上了。

当时的connectionString如下:

<add name="masterEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-MBBGC2M;initial catalog=master;integrated
security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

说实话那些metadata为啥长那个样子,我真是不明白。因为这个配置,项目在发布到本机,从浏览器直接登陆时,发现无法连接到DB。于是一顿修改上述的字符串。

第一次,修改为这个样子:

<add name="masterEntities" connectionString="Data Source=127.0.0.1;Initial Catalog=master;uid=sa;pwd=sa;"  />   

把那些乱七八糟的东西都去掉了,结果发现连开发环境都连不上了,提示的错误是:

{"The connection string 'masterEntities' in the application's configuration file does not contain the required providerName attribute.\""}

然后把人家要的providerName加上去:

 <add name="masterEntities" connectionString="Data Source=127.0.0.1;Initial Catalog=master;uid=sa;pwd=sa;"  providerName="System.Data.SqlClient" />   

还是有问题,错误提示是:

{"The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.  This will not work correctly. To fix this problem do not remove the line of code that throws this exception.
If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection
and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715"}
可见直接修改Web.config不靠谱。所以狠了狠心,把*.edmx从项目中删除,重新生成,这一次,服务器选择填写IP(127.0.0.1),连接方式使用SQL Server方式。填写好后,连接字符串自动被修改为下面的样子。注意,事先在Web.config中把原来的那个删除掉。

 <add name="masterEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=127.0.0.1;initial catalog=master;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" /></connectionStrings>

可见,那些乱哄哄的metadata配置还是有用的。更新后,在开发环境DB连接正常,数据可以保存到DB中。

然后把这个Web.config复制到发布文件夹。

再次测试,在发布环境也工作了。

这样,如果我把发布环境移到其他计算机上,应该只需要修改IP地址就可以了。

但愿我的经验可以给您节约些时间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐