问题
I'm developing a DataBase First EF application and everything is working great with the auto-generated code and app.config sections. But when I try to remove the connection string of the app.config and put it as parameter on the DbContext constructor I cannot get it to work.
The connection string in the app.config:
<add name="EntityContext"
connectionString="metadata=res://*/ModelHistory.csdl|res://*/ModelHistory.ssdl|res://*/ModelHistory.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="DATA SOURCE=XXXXX;PASSWORD=xxxxx;PERSIST SECURITY INFO=True;USER ID=XXXX""
providerName="System.Data.EntityClient" />
And im trying to pass it via constructor:
public EntityContext() : base(GetConnectionString()) { }
private string GetConnectionString()
{
return metadata=res://*/ModelHistory.csdl|res://*/ModelHistory.ssdl|res://*/ModelHistory.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="DATA SOURCE=XXXXX;PASSWORD=xxxxx;PERSIST SECURITY INFO=True;USER ID=XXXX""
}
But it throws the error:
Additional information: Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.
回答1:
We need to move the connection string from app.config file to the code. This can be done in context.cs file. In the constructor you need to specify the connection string In your connection string you need to replace Replace quote " with '(single quote)
public partial class ProducerCentralEntities : DbContext
{
public ProducerCentralEntities()
: base(@"metadata = res://*/TestProj.csdl|res://*/TestProj.ssdl|res://*/TestProj.msl;provider=System.Data.SqlClient;provider connection string=';data source=serverName;initial catalog=databaseName;integrated security=True;MultipleActiveResultSets=True;application name=EntityFramework';")
{
}
}
Note: 1) You should have complete connection string 2) Replace quote " with '
来源:https://stackoverflow.com/questions/26065626/how-to-pass-a-ef-db-first-connection-string-via-constructor-instead-put-in-app-c