How To Change Connection String at runtime using CTP5 - c#

all
I am trying to change the connection string at runtime, i am using CTP5,
when i change the connection string and the folder is empty EF throws:
Database 'C:...\bin\Debug\db.mdf' already exists. Choose a different database name.
Cannot attach the file 'C:...\bin\Debug\DB\db.mdf' as database 'DB'.
when the folder has db.ldf (The Log File) and db.mdf EF throws the same exception
Please Help...

In Entity Framework 4 you can create an ObjectContext with a connection string as constructor argument. So you're free to use any connection string any time. If course it would help if the database structure matched the context :).

You can change the app config and reload changes.
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Copy the value of new connection string
config.AppSettings.Settings["ConnectionString"].Value = "New Connection String";
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");

Related

How do I create a generic file path to a local database in a C# Application?

I have a simple data entry Windows Form with a datagridview display that links to a local database. When I run the program and try to add data on another computer, I get this message:
Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.
An attempt to attach an auto-named database for file C:\Users\roberto.yepez\Documents\Visual Studio\2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
The file path is to the path on the computer where I coded the program.
Here is my code:
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True".ToString());
I am a self-taught coder, please help! :)
I believe you're running into a problem because your local sql server to which your code is trying to attach the StudentInfo1.mdf (whose path is in the connection string) already contains a database called StudentInfo1 - it decided to try and create a database of this name based on the name of the mdf file. I'm guessing that you can pick your own name by specifying Initial Catalog in your connection string but this would mean there are two databases with possibly the same set of tables and a potential for confusion
Per the comment I posted I would instead advocate that you use SQL Server Management Studio to permanently attach your db (you make have already done this) and then adjust your connection string so that it refers to the permanently attached db. This reduces the chances that your next question will be "my code says it's updating my db but I cannot see any changes!?"
Please move this connection string
"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True"
to app.config file. When you deploy to production, change the paths in that app.config, according to the production machine settings.
You can even apply transformations on the app.config to deploy in various machines/scenarios.

Database first EF and ASP.NET Core 3 Web API published on Azure, connection string error

I'm developing an ASP.NET Core 3 Web API with a database first generated db context.
I have the connection string in the appsettings.json file.
Everything is fine when I run it locally on IIS Express.
The problem is that when I publish it on Azure, it gives me the error:
System.ArgumentException: Keyword not supported: 'data source'.
[...]
I noticed that the connection string, when published changed from:
metadata=res://*/DTOs.csdl|res://*/DTOs.ssdl|res://*/DTOs.msl;provider=System.Data.SqlClient;provider connection string='data source=*****;initial catalog=*****;persist security info=True;user id=*****;password=*****;MultipleActiveResultSets=True;App=EntityFramework'",
to:
metadata=res://*/DTOs.csdl|res://*/DTOs.ssdl|res://*/DTOs.msl;provider=System.Data.SqlClient;provider connection string="data source=*****;initial catalog=*****;persist security info=True;user id=*****;password=*****;MultipleActiveResultSets=True;App=EntityFramework""
As a work around I changed the line
services.AddScoped<palmdtos>(_ => new MyDbContext(Configuration.GetConnectionString("myConnectionString")));
to
services.AddScoped<palmdtos>(_ => new MyDbContext(Configuration.GetConnectionString("myConnectionString").Replace(""","'").Replace("&", "&")));
Is there a better way to do it?
Models created with the EF Designer are different from Code First in that your model already exists and is not generated from code when the application runs. The model typically exists as an EDMX file in your project.
The designer will add an EF connection string to your app.config or web.config file. This connection string is special in that it contains information about how to find the information in your EDMX file.
Refer to this article.
The cause was the connection string for one of the EDMX files we were using. Since the EDMX has to be read-only, we had to use a different connection string in Azure.
When replacing &quote; by a single quote ', it will work fine again. So go to azure website > Configuration > Connection strings > add your conn string with custom type.
Note: Make sure you also select Custom instead of SQLAzure for your Entity Framework connection string, even though the database runs on Azure.
Can you try updating the settings?
In Azure Panel:
Select App -> Application Settings -> Enter new Connection String -> Save

Azure function using entity framework but connect string not working

I have a azure V1 function using a project dll that handles entity framework.
First I set connect string like
metadata=res://*/Dev.csdl|res://*/Dev.ssdl|res://*/Dev.msl;
provider=System.Data.SqlClient;
provider connection string='
data source={IP};initial catalog={DBName};
persist security info=True;
user id={User};password={PW};
MultipleActiveResultSets=True;
App=EntityFramework'
and I got
Keyword not supported: 'metadata'.
then I changed my connect string to
data source={IP};initial catalog={DBName};persist security info=True;user id={User};password={PW};
and I got
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
And here's my code
DevEntities db = new DevEntities();
var lstAcAccount = db.AcAccounts.ToList();
return req.CreateResponse(HttpStatusCode.OK, lstAcAccount);
DevEntities is from other dll project that using the connect string above.
So, what should I do to make this work?
You shouldn't use generated connection string, now you have all metadata files included in your solution. Instead try use in connection string section of app.config:
"data source=localhost\sqlexpress; initial catalog=sample; integrated security=True;MultipleActiveResultSets=True;"
If it is Database first:
Open the .edmx[Diagram] -> right click -> "Update Model from database"
And see if the will appear the "Add", "Refresh" and "Delete" tabs.
If doesn't... probably your connection is broken and the dialog for VS creates a new connection string will appear instead.
Hope it helps.

Entity Framework 5 : changing the database connection

I have a made an EntityFramework model based on my Demo Database.
I want to include connection strings for Staging and production and then in my Console App prompt the user to see which database they want to perform the operation on.
When I was prompted to setup the EF.edmx file I just chose to store the connection string in the app.config file. I have seen a link to change the Connection string of EntityFramework Context when initializing it here
However when I store another connection to my Staging Database, I get an error "Keyword not supported: 'metadata'"
So I stripped down the connection string not to include the EntityFramework type of parameters such as metadata=res://*/MyDBItems.csdl|res://*/MyDBItems.ssdl blah blah
and used a very simple database connection string
data source=myDB;initial catalog=myDB;user id=myUser;password=myPass;MultipleActiveResultSets=True;
now my Context does instanciate but when I get to a query I get another error about:
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.
How can I switch between different databases with Entity Framework 5, thanks!
forget it I got it....what I did...I made a 2nd constructor in the Context.cs file
public MyContext(string dbModel) : base("name="+dbModel) {
}
then in my app.config I have the various settings for the Demo,Staging & Production database connections....this took the full entityframework connection string. I think the link I provided was for Code-First but I am using Database First.

Need changable App.config file in WPF

I have a desktop WPF application which uses Entity Framework 4.1 Code First approach to manage data.
EF adds a connection string to the App.config file and I wan't to be able to change this connection string at runtime.
Scenario is like this:
When I deploy the application it has a default connection string in the App.config file. The user runs the application and since the connection string will probably be invalid for the user (because of server name, user id and password) I will display a server configuration window.
Here user will enter the valid information about his connection and press OK. I will then be able to change the App.config file and save the user's new valid information to the file.
Problems:
If I change it using ConfigurationManager, the changes will be temporary meaning that the file is not saved, changes are made in memory.
If I read the App.config file into a stream, make required changes in the memory, delete physical file and save the in memory stream as App.config again, Windows will not let me make changes to files under ProgramFiles folder.
What is would be the best approach here?
EDIT: Problem Again!
After I modify the App.config file with this method:
private void ApplyChangesToConnectionString()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
config.Save(); // This line throws an exception
ConfigurationManager.RefreshSection("connectionStrings");
}
config.Save(); method call throws an error saying
"Access to "C:\Program Files (x86)\MyCompany\MyApp\MyApp.exe.config"
is denied."
I know that files under "Program files" are immutable, so how can I handle this?
I couldn't modify ConfigurationManager.ConnectionStrings["key"] object, because it is readonly.
So I decided to add a new connection string to my App.config file so it looks like this:
<connectionStrings>
<add name="SomeUniqueName" connectionString="Data Source=(local)\SQLExpress;Initial Catalog=MyDb;User Id=sa;Password=password; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
and then changed my DbContext constructor to take newly added connection string like this:
public MyContext()
: base("name=SomeUniqueName")
{
}
Here, the value of name attribute at connection string and constructor must match.
Then to change this newly added connection string at runtime I used a method like this:
private void ApplyChangesToConnectionString()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
App.config is not the proper place to do this since it's a global configuration used by the application.
I recommend you to save the settings per user. See this related question : c# - approach for saving user settings in a WPF application?
App.config is the correct approach in my opinion, however I wouldn't rely on writing the file physically yourself. Instead, allow the framework to do the heavy lifting for you.
Check out the sample here.
EDIT: Glad Sandeep's comment above has helped you. Feel free to check out that link too if you want a bit more information!

Categories