【问题标题】:C# Connection string issue. EF code first and db contextC# 连接字符串问题。 EF 代码优先和数据库上下文
【发布时间】: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


【解决方案1】:

只给base("BlogDB")

 public class BloggingContext : DbContext
 {
public BloggingContext()
    :      base("BlogDB")
  {
  }

public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; } 
 }

【讨论】:

  • 现在根据您的代码进行更改后出现此错误。 An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll Additional information: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.
  • 可能是 app.config 文件中的连接字符串不正确。只是不明白那里要改变什么。
【解决方案2】:

您没有正确输入连接名称。 您可以如下所示更改您的代码

public class BloggingContext : DbContext
{
    public BloggingContext()
        : base("name=BlogDB")
    {
    }

    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

或者直接连接字符串

public class BloggingContext : DbContext
{
    public BloggingContext()
        : base(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\tmks.dldp\documents\visual studio 2013\Projects\CodeFirstTest\CodeFirstTest\DB\Test.mdf;Integrated Security=True")
    {
    }

    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多