13

我使用實體框架4與我的Asp.Net MVC3應用程序。我的問題是,我正在使用實體框架來執行與我的數據庫的行動,這是工作正常。爲了其他目的,我也使用Sql連接來存儲和從數據庫中檢索我的數據。我得到不支持的關鍵字:'metadata'。?與Entityt框架與MVC3的Sql連接

[Keyword not supported: 'metadata'] 

與我的數據庫連接時出錯。

這是我的web配置

<add name="VibrantEntities" connectionString="metadata=res://*/Vibrant.csdl|res://*/Vibrant.ssdl|res://*/Vibrant.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=KAPS-PC\KAPSSERVER;initial catalog=vibrant;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 

我使用的類庫,所以這是我的應用程序配置。

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> 

    <add name="VibrantEntities" connectionString="metadata=res://*/Vibrant.csdl|res://*/Vibrant.ssdl|res://*/Vibrant.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=KAPS-PC\KAPSSERVER;initial catalog=vibrant;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 

回答

20

ADO.NET的連接字符串(本例中爲SqlConnection)不採用該格式。您正在使用特定於實體框架的那個。 ADO.NET的一個應該是這樣的:

"data source=KAPS-PC\KAPSSERVER;initial catalog=vibrant;integrated security=True" 

所以,概括起來講,你需要兩個單獨的連接字符串,一個用於EF和一個ADO.NET

-1

這裏theres一個更好的解決方案,使用Entity Framework Power工具,將數據庫逆向工程到您的項目中,然後在兩種情況下都可以使用一個EF連接字符串(這是一個正常的連接字符串)。

+0

我沒有得到你,你能解釋更多 –

5

另一種選擇(不是同一事物的兩個獨立的連接字符串等)是建立從實體框架對象返回ADO.NET連接字符串的方法:

using System.Data.EntityClient; 
using System.Data.SqlClient; 
... 
private string GetADOConnectionString() 
{ 
    SalesSyncEntities ctx = new SalesSyncEntities(); //create your entity object here 
    EntityConnection ec = (EntityConnection)ctx.Connection; 
    SqlConnection sc = (SqlConnection)ec.StoreConnection; //get the SQLConnection that your entity object would use 
    string adoConnStr = sc.ConnectionString; 
    return adoConnStr; 
} 

(我把這個某處我的類庫在我的EDMX文件)

(我得到這個從http://justgeeks.blogspot.com/2009/11/getting-sqlconnection-from.html

甚至更​​好......如果你的SQLConnection東西都是手工操作的SQL查詢,跳過的SQLConnection完全通過ExecuteStoredCommand:

new AdventureEntities().ExecuteStoreCommand(
     @" UPDATE Users 
       SET lname = @lname 
       WHERE Id = @id", 
     new SqlParameter("lname", lname), new SqlParameter("id", id)); 

(我得到這個從Entity Framework getting an sql connection

10

您連接字符串是特定於實體框架和包含元數據。你需要從它得到你的提供者連接字符串。您可以使用EntityConnectionStringBuilder做到這一點:

var efConnectionString = "Your Entity Framework connection string"; 
var builder = new EntityConnectionStringBuilder(efConnectionString); 
var regularConnectionString = builder.ProviderConnectionString; 
+1

短,精確和易於理解的!謝謝 –

+0

嗨,我應該在哪裏寫這個代碼?它在web.config中嗎? – kurniawan26

+0

@ kurniawan26你不能在你的'web.config'中編寫C#代碼。無論連接到數據庫的哪個位置,都需要使用它。雖然你的連接字符串應該存在於'web.config'中。您可以在單獨的問題中發佈您的代碼,我會很樂意提供幫助。 –

相關問題