【问题标题】:Entity Framework 6 - can't connect to database serverEntity Framework 6 - 无法连接到数据库服务器
【发布时间】:2014-06-24 03:04:05
【问题描述】:

此行导致异常:

var query = from customer in ctx.Customers select customer;

例外:

EntityFramework.dll 中出现“System.Data.Entity.Core.ProviderIncompatibleException”类型的未处理异常

从数据库获取提供者信息时出错。这可能是由 Entity Framework 使用不正确的连接字符串引起的。检查内部异常以获取详细信息并确保连接字符串正确。

来自Database.Connection.ConnectionString的连接字符串:

Data Source=.\SQLEXPRESS;Initial Catalog=Customer.CustomersContext;Integrated Security=True;MultipleActiveResultSets=True

App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
  <connectionStrings>
  <add name="Customer.CustomersContext" providerName="System.Data.SqlClient" connectionString="Data Source=(localdb)\Projects;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False" />
</connectionStrings>
</configuration>

Context类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

namespace Customer
{
    class CustomersContext : DbContext
    {
        public CustomersContext() : base("Customer.CustomersContext")
        {
            System.Console.WriteLine(Database.Connection.ConnectionString);
        }

        public DbSet<CustomerDb> Customers { get; set; }
        public DbSet<Contact> Contacts { get; set; }
    }
}

您可以看到我什至尝试将连接字符串名称从app.config 传递给上下文构造函数(应该使用localdb),但打印的连接字符串仍然是SQLExpress

【问题讨论】:

  • 我认为您需要配置 SqlConnectionFactory 而不是 LocalDbConnectionFactory,后者使用稍微不同的连接字符串格式。

标签: c# .net sql-server entity-framework


【解决方案1】:

看看this。如果您使用的是 localdb,则需要相应地更改连接字符串。所以,你的连接字符串应该是 Data Source=(localdb)\v11.0;Integrated Security=true;AttachDbFileName=C:\Path-to-your-database.mdf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 2021-10-02
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多