【发布时间】:2017-01-10 16:56:28
【问题描述】:
我的带有连接字符串的配置文件如下所示
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="BlogDB"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\tmks.dldp\documents\visual studio 2013\Projects\CodeFirstTest\CodeFirstTest\DB\Test.mdf;Integrated Security=True"/>
</connectionStrings>
</configuration>
上面的连接字符串可以吗?
以下方式连接字符串已传递到数据库上下文。
public class BloggingContext : DbContext
{
public BloggingContext()
: base(ConfigurationManager.ConnectionStrings["BlogDB"].ConnectionString)
{
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
我在运行代码时收到此错误。错误如下
未处理的类型异常 'System.Configuration.ConfigurationErrorsException' 发生在 System.Configuration.dll
附加信息:配置系统初始化失败
告诉我 app.config 文件中的代码或连接字符串有什么问题?
谢谢
【问题讨论】:
-
我认为连接字符串设置缺少提供程序类型,如 providerName="System.Data.SqlClient" ...这可能是问题
-
所以给我更正的代码。
-
尝试添加
Initial Catalog=...,例如:Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\tmks.dldp\documents\visual studio 2013\Projects\CodeFirstTest\CodeFirstTest\DB\Test.mdf;Initial Catalog=Test;Integrated Security=True -
首先,为什么要把连接字符串放在app.config中。是否在任何具有 web.config 文件的 Web 项目中都没有引用此类库。如果您正在使用任何 Web 项目,那么最好将连接字符串保留在 web.config 中并在您的类库中引用它们。
-
我将连接字符串放在 app.config 文件中,我正在使用控制台应用程序。
标签: c# entity-framework connection-string