I'm dealing with a C# application using EntityFramework and an object derived from DbContext.
I need to set programmatically the connection string when a new instance of MyDbContext object is created. In order to do so I use the following code:
public MyDbContext(string myString)
{
this.Database.Connection.ConnectionString = myString
}
myString = "Server=MYSERVER\\SQLEXPRESS; Database=MyDB; User ID=user; Password=pass;";
or
myString = "Data Source=|DataDirectory|\\AirecCalcDatabase.sdf";
The database providers are different for the two strings. SQLExpress for the first one, SQLCompact for the second one.
If I try to run this code with the first string, I get ArgumentException coming from the connection string. For example "Keyword not valid: server" but also "Keyword not valid: database". The connection string works when using the DbContext with no arguments, which is, reading the string from app.config
When you're wanting to use CE, you may need to change the DefaultConnectionFactory to point to SQL CE:
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
See this blog post for more information
Related
I'm creating an Azure Function and I've added a reference to a project that uses Entity Framework. I've copied the connection string from that project and pasted in the local.settings.json file inside the ConnectionStrings object as a valid EF connection string.
metadata=res://*/xxx.csdl|res://*/xxx.ssdl|res://*/xxx.msl;
provider=System.Data.SqlClient;
provider connection string="e;
data source=xxx;
initial catalog=xxx;
user id=xxx;
password=xxx;
MultipleActiveResultSets=True;
App=EntityFramework
"e;
But it's given me this exception:
Keyword not supported: metadata.
If I use a valid SQL connection string (like below),
data source=xxx;
initial catalog=xxx;
user id=xxx;
password=xxx;
MultipleActiveResultSets=True;
App=EntityFramework
I've this exception:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
How could I create a connection to my database in an Azure function using Entity Framework? I'm using .NET framework and for EF I'm using database first.
I'm init my database context as follow:
using (XxxDB db = new XxxDB())
{ }
Meanwhile, I've created an overload for the contrustor XxxDB
public XxxDB(string connectionString): base(new EntityConnection(connectionString), true)
{ }
And pass the SQL connection string when creating the XxxDB and got this error:
Keyword not supported: data source.
Ok, this is caused by how EF model first connection strings are generated. The EF connection string builder requires a plain connection string in the constructor. Then you add the metadata section for model first.
When you create new connection string to pass to a DB context string builder, change this:
public XxxDB(string connectionString): base(new EntityConnection(connectionString), true)
{ }
to
public XxxDB(string connectionString): base(GetEntityConnection(connectionString), true)
{ }
private static string GetEntityConnection(string connectionString)
{
var efConnection = new EntityConnectionStringBuilder();
efConnection.ProviderConnectionString = connectionString;
// res://*/xxx.csdl|res://*/xxx.ssdl|res://*/xxx.msl
var model = "xxx";
// this is what's missing in your question
efConnection.Metadata = string.Format("res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", model);
return efConnection.ConnectionString;
}
I have a solution consisting of 4 projects. MVC, WCF, Business LYR, DataAcess. I am using entity framework for database transaction. My requirement is that i want to fetch the entity connectionstring only from MVC webconfig without refering in APP.cofig of acess layer. Is it possible in this scenario?
While I tried the following code I got an error.
this.ConnectionString="data source=cmh-sosql;initial catalog=Student;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(this.ConnectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/schoolModel.csdl|res://*/schoolModel.ssdl|res://*/schoolModel.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
using (SchoolDB schoolDB = new SchoolDB(ecb.ConnectionString))
Error: The entity type student is not part of the model for the current context.
You are absolutely correct. I got the solution. There is no need to keep any string in webconfig for reference to a entity model. We can use the above code for reference it. But the change is to configure the context object.
public SchoolDB(string connectionString)
: base(connectionString)
{
}
We need to change the constructor also by this format.
thanks Sampath
I'm using Entity Framework 5 with Code First. I've written a custom IDbConnectionFactory which I want to use for all the connections made by my DbContext class, so early on in the application's lifecycle, before any database work is done, I call
Database.DefaultConnectionFactory = new MyConnectionFactory();
However, MyConnectionFactory.CreateConnection is never called, which suggests to me that EF's changed it back - but the debugger shows that it's still a MyConnectionFactory after several queries have run. For some reason, it's just not using it.
My DbContext is initialised by passing the name of a connection string from the app.config file, and those connection strings do specify an explicit provider (as indeed they have to) so I'm wondering if that's causing a per-connection override of the connection factory based on the connection string. Does this happen and can I stop it without registering a completely new provider (although maybe that's not too hard to do?).
Whatever I see online about this (much obscured by the defaultConnectionFactory tag in various app.config examples) suggests you can just change it to an IDbConnectionFactory instance of your choice and it'll work, but mine isn't behaving.
The purpose of this is to allow me to run a particular set of SQL statements whenever a new connection is opened, so the second part of this question would be does anybody know a better way to do this?
I know it is not ideal but this worked for me:
public class DBBase : DbContext
{
public DBBase(string nameOrConnectionString)
: base(Database.DefaultConnectionFactory.CreateConnection(nameOrConnectionString), true)
{
}
// ...
}
You need to get the connection that you built for each call that you are wanting to use. For example using the following code.
private static void UsingCustomConnection()
{
using (var conn = Database.DefaultConnectionFactory.CreateConnection("YourDbName"))
{
using (var context = new YourContext(conn))
{
context.Destinations.Add(new Destination {Name = "Colorado"});
context.SaveChanges();
}
}
}
You will need to setup this in YourContext
public YourContext(DbConnection connection)
: base(connection, contextOwnsConnection: false)
{
}
I have several databases, the schema of them are same. When I use database-first, the connection string is specified when I create the edmx file. I want to know, is there a way to change the connection string? This is, so I can choose which database to operate.
We do not store connection strings in our web.configs, so the accepted solution would not work for us. If you simply attempt to provide the connection string via the base DbContext constructor, you'll get the following exception:
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.
To resolve this, create a partial class of your context as follows and format your connection string with the additional EF metadata (where MyContext is your context model name (e.g. your model name is MyModel.edmx, than the MyContext in code below is replaced with MyModel with all three extensions .csdl, .ssdl, .msl used)):
public partial class MyContext
{
public MyContext(string connStr)
: base(string.Format(#"metadata=res://*/MyContext.csdl|res://*/MyContext.ssdl|res://*/MyContext.msl;provider=System.Data.SqlClient;provider connection string='{0}'", connStr))
{
}
}
Change the connection string in the web.config file.
<connectionStrings>
<add name="SandBoxEntities" connectionString="metadata=r... />
</connectionStrings>
I abbreviated the actual connection string because it isn't important -- just wanted to give you an idea of what to look for in the web.config file.
You can also change your connection strings programatically. Check out Example 16.2. Programmatically modifying an EntityConnectionString.
You can define multiple connection string in web.config and then use them in your code perhaps your job.
for example:`
<connectionStrings>
<add name="conStr1" connectionString="metadata=r... />
</connectionStrings>`
<connectionStrings>
<add name="conStr2" connectionString="metadata=r... />
</connectionStrings>`
and so on
and your context class constructor get connection string name as parameter:
public MyContext(string connStr)
: base(connStr) { }
Ok. now you can use in your code as below:
using (var db = new MyContext("name=conStr1"))
{
//your code here
}
and then
using (var db = new MyContext("name=conStr2"))
{
//your code here
}
I want to use Entity Framework without app.config file.
I want to define a string variable Connection String in my code and use that to connect to the database.
Please show me the way if it is possible.
You're not mentioning what approach you're using (database-first, model-first, code-first) - but basically, in the end, you need to define a string variable and assign it a valid EF connection string
string myConnectionString = "...(define a valid EF connection string here)......";
Example for database-first approach:
string myConnectionString = #"metadata=.\Model1.csdl|.\Model1.ssdl|.\Model1.msl;provider=System.Data.SqlClient;provider connection string="";data source=.;initial catalog=test;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""";
and then use that to create your ObjectContext (database- and model-first) or DbContext (code-first)
using(ObjectContext ctx = new ObjectContext(myConnectionString))
{
// do your EF magic here.....
}
But quite honestly - I think this is a really bad idea since this makes it impossible for you to move your application to another machine - no one else can install and run this, since the connection string is hard-coded into your C# code..... the whole point of having config files is so that you can change / adapt things like connection strings so that they are not tied to a single machine/location but can be adapted to the particular needs of a given user / customer....