Get connection string from web.config to use in EF POCO? - c#

I've noticed that when I create model-first database using EF it is ignoring web.config connection strings and doing it's own thing in the background. Then I found a way to set my own connection string in constructor like so.
public class MainDataContext : DbContext
{
public MainDataContext()
{
this.Database.Connection.ConnectionString = "MY CONNECTION STRING THAT IS ACTUALLY USED";
}
}
Question: How can I force/set it to use connection string from web.config?
I've been told that if you name your connection string just like your data context it will work but it doesen't for me. I know for sure that it does not work if I name it DefaultConnectionString.
<add name="MainDataContext" providerName="System.Data.SqlClient"
connectionString="Server=(LocalDB)\\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|ProjectDB.mdf;" />
Error occurred when I try to do update-database -v -f from console.

You can try something like this:
public MainDataContext() :
base(typeof(MainDataContext).Name)
{
}
Are you sure your connection string declaration in the Web.config is correct? Like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyDatabase" connectionString="server=localhost;User Id=user;password=password;Persist Security Info=True;database=mydatabase" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>

Related

ConfigurationManager ConnectionString not working

I have this project I am working on and I want to "hide" my connection string from my main class and place it to the App.Config.
While trying to access the connection string from the main class I get this error "System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null."
This is my main class code that I use to get the conn string:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString.ToString();
This is my App.Config code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="ConnString" connectionString="Password=XXXX;Persist Security Info=True;User ID=XXXX;Initial Catalog=XXXX;Data Source=XXXX"/>
</connectionStrings>
</configuration>
Note: I have to add the app.config by myself as a new class.
Also the connection string works perfect when it's in the main class, so it's not its fault.
The WebConfig connection string should be like this:
<connectionStrings>
<add name="DBCS" connectionString="server=.;database=MVCCrud;integrated security=SSPI" providerName="Sql.Data.SqlClient" />
</connectionStrings>
The main class connection string should be like this:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
I added config, added you code and configuration and it worked.
I can't add this as a comment, as I can't post images there, that's why I am writing an answer.
So, just to make sure you added the file in a correct way:
right click your project, add -> new item:
and then just find appropriate file to add (you can make use of search text box):

ASP.NET MVC C# Connection String metadata creation

Sorry, I have a feeling this is a really basic question, but my connection string to my data source is invalid. I did a bit of trouble shooting and think that I am missing the metadata part of the connectionstring - but I'm not sure where it is/how to create it.
How is how I think it should look
<add name="PDCWebEntities" connectionString="metadata=METADATASTRING;Data Source=.;Initial Catalog=PDC;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
And here is where I think the information that needs to be in the metadata string is held:
It should be noted that the app.config file where the connectionstring is is in the PokemonDayCareSimple.Web project
Is it possible to make the metadata part of the string from this information?
You don't need metadata for connectionString.
<add name="DefaultConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\me\source\repos\MarketplaceMVC\MarketplaceMVC.Web\App_Data\MarketplaceIdentityDb.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
Instead of "AttachDbFilename" you can use also "Initial Catalog".
In your Context Class you need to add a constructor:
public ApplicationContext() : base("DefaultConnection")
{
}

ASP.Net can't see my database from the ISS

I decided to learn how to make a simple ASP.Net project, with a reference to a database project through the Repository Pattern.
I have my Controller calling for a List<Weight> to handle:
public IActionResult MyWeight()
{
var repo = new Database.Repositories.WeightRepository();
var data = repo.GetWeight().Result;
return View(data);
}
When repo.GetWeight() is called, I get an AggregateException error, with an inner exception saying:
"No connection string named 'MyDatabaseConnection' could be found in the application config file."
So for clarity, let me outline the solution's structure:
aspProj
Controllers
Views
Service
App.config (1)
Web.config
...
Database
Entities
Repositories
App.config (2)
...
Database.Test
Test.cs
App.config (3)
...
I've added the following connectionString to all App.configs and the Web.config:
<connectionStrings>
<add
name="MyDatabaseConnection"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
I have tested the database both from Visual Studio's Server Explorer, and through the Test.cs file from the test-project. I can insert data and retrieve without a problem.
But when the ASP.Net-part wants to access it, there is no love.
I thought it might be the ISS which did not know the path from where it is...
Any thoughts?
__
Edit:
My Web.config:
My AppSetting.json:
Well the problem is clear - ASP.NET is trying to access the database using a connection string with the name MyDatabaseConnection:
<connectionStrings>
<add name="MyDatabaseConnection" connectionString="put the connection to the db here..." />
</connectionStrings>
And in your Web.config you only have a connection string with the name WeightDatabaseConnection:
<connectionStrings>
<add name="WeightDatabaseConnection" connectionString="put the connection to the db here..." />
</connectionStrings>
Just add a new element for MyDatabaseConnection under <connectionStrings> in the Web.config file and it should work

Incorrect connection string? Error: An attempt to attach an auto-named database failed

Solution: Add the directory to your connection string in the app.config file and the Settings.setting file in the properties section of your project. My working connection string ended up being <Value Profile="(Default)">Data Source=(LocalDB)\v11.0;AttachDbFilename=F:\hi\prgrm\ProgramName\Database1.mdf;Integrated Security=True</Value>
Once I run my program I get the following error:
An attempt to attach an auto-named database for file F:\Graded unit
2\SimplyRugby\LollipopUI\bin\Debug\Database1.mdf failed. A
database with the same name exists, or specified file cannot be
opened, or it is located on UNC share.
The method that makes the error happen:
public bool CheckUsername(string username)
{
var usernameResult = (from person in dbContext.Persons
where (person.Username == username)
select person.Username).FirstOrDefault();
//stores username if a username is found
return !(string.IsNullOrEmpty(usernameResult));
// if no correct user found from query return false else true
}
After some research apparently it's that the connection string is wrong. I had a little play with some suggestions online but I'm not too sure what is incorrect and how to fix it so I've been going around in circles for the past five or so hours.
My app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="LollipopUI.Properties.Settings.Database1ConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Thank you for your time.
Try to make User Instance property as true like
User Instance=True
in your connection string.
You can also refer to this related thread which says that your connection string should looks something like this:
<connectionStrings>
<add name="Sales_DBEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string='server=YourServerNameHere;database=Sales_DB;integrated security=True;App=EntityFramework'"
providerName="System.Data.EntityClient" />
</connectionStrings>
I have faced that situation and I resolved it like this.
Go to Setting of DataBase and set option **Copy to output Directory** to **Copy if Newer**
the problem will solve
Late response is better than no response at all:
The issue was that my connectionString wasn't mapped to the database location.
Edit: I'm not sure what the path I used was as it was so long ago but if you have this issue try using a full hardcoded path to the .MDF file. After you've confirmed it works then you can start fiddling around with it.

Putting a connection string in the web config

So I'm using C# and I've got the following SQL connection string:
private static string _conn = Properties.Settings.Default.dBizConnectionString;
And I'd like to know if and how I can put it in the web config and app config? Thanks for the help!
Here's a blog post from Scott Forsyth explaining everything:
Using Connection Strings from web.config
The short answer is yes, like so:
<connectionStrings>
<add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Server=ServerName; Initial Catalog=InitialCatalog; User ID=User; Password=Password; MultipleActiveResultSets=True;" />
</connectionStrings>
There's a lot of information out there about connection strings. There are more options you can specify, they can be encrypted, etc. etc., but this will get you started.
Add it to the web config like this:
<connectionStrings>
<add name="myConnectionStringName" connectionString="Data Source=mySqlServerInstance;Initial Catalog=myCatalog;User ID=myUserId;Password=myPassword"/>
</connectionStrings>
Add code to retrieve it:
private static string GetConnectionString()
{
var config = WebConfigurationManager.OpenWebConfiguration("/myProject");
var connections = config.ConnectionStrings;
var settings = connections.ConnectionStrings["myConnectionStringname"];
string connectionString = settings.ConnectionString;
return connectionString;
}

Categories