1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

To what should I set the Database.DefaultConnectionFactory if I want to use an SQLexpress server?
You can use new SqlConnectionFactory, with a connection string. See this post on msdn for more info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.