2014-05-07 166 views
1

該行導致異常:實體框架6 - 無法連接到數據庫服務器

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

例外:

類型的未處理的異常「System.Data.Entity.Core.ProviderIncompatibleException '發生在EntityFramework.dll中

從數據庫獲取提供者信息時發生錯誤。這可能是由實體框架使用不正確的連接字符串造成的。檢查內部異常以獲取詳細信息,並確保連接字符串正確。從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; } 
    } 
} 

你可以看到我甚至試圖通過連接ST環名從app.config到上下文構造函數(應該使用localdb),但打印的連接字符串仍然是SQLExpress

+0

這是實力將有助於你 http://stackoverflow.com/questions/18355803/system-data-entity-core-providerincompatible-exception-in- mvc-5 –

+0

我認爲你需要配置'SqlConnectionFactory'而不是'LocalDbConnectionFactory',它使用稍微不同的連接字符串格式。 –

回答

1

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