C# 实体框架6-can';无法连接到数据库服务器
此行导致异常:C# 实体框架6-can';无法连接到数据库服务器,c#,.net,sql-server,entity-framework,C#,.net,Sql Server,Entity Framework,此行导致异常: var query = from customer in ctx.Customers select customer; 例外情况: EntityFramework.dll中发生类型为“System.Data.Entity.Core.ProviderIncompatibleException”的未处理异常 从数据库获取提供程序信息时出错。这可能是由于实体框架使用了不正确的连接字符串造成的。检查内部异常以了解详细信息,并确保连接字符串正确 数据库中的连接字符串。连接。连接字符串:
var query = from customer in ctx.Customers select customer;
例外情况:
EntityFramework.dll中发生类型为“System.Data.Entity.Core.ProviderIncompatibleException”的未处理异常
从数据库获取提供程序信息时出错。这可能是由于实体框架使用了不正确的连接字符串造成的。检查内部异常以了解详细信息,并确保连接字符串正确
数据库中的连接字符串。连接。连接字符串:
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>
您可以看到,我甚至尝试将连接字符串名称从app.config
传递给上下文构造函数(应该使用localdb),但打印的连接字符串仍然是SQLExpress
<。如果您使用的是localdb,则需要相应地更改连接字符串。因此,您的连接字符串应该是
数据源=(localdb)\v11.0;综合安全=真实;AttachDbFileName=C:\Path to your database.mdf
这可能会对您有所帮助。我认为您需要配置SqlConnectionFactory
,而不是使用稍微不同的连接字符串格式的LocalDbConnectionFactory
。
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; }
}
}