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
Related
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):
I have the next connectionstring file:
<?xml version="1.0"?>
<connectionStrings>
<add name="DefaultConnection"
connectionString="Application Name=CalculatorTest;Server=PC01;Initial catalog=MyDB;Integrated Security=true" />
</connectionStrings>
I want to add a new connection, for example "MyDBTest", staying:
<?xml version="1.0"?>
<connectionStrings>
<add name="DefaultConnection"
connectionString="Application Name=CalculatorTest;Server=PC01;Initial catalog=MyDB;Integrated Security=true" />
<add name="NewDefaultConnection"
connectionString="Application Name=CalculatorTest;Server=PC01;Initial catalog=MyDBTest;Integrated Security=true" />
</connectionStrings>
How do I do it from C# Mvc 5?
Right click on your project and add an Entity Data Object, then enter the name you want it to be called; chose code first from database, then enter the server address and you can also select which tables from the db you want.
This will create the connection string for you. I would however recommend doing this in a separate class library so it’s easier to maintain. Note: if you do use it in a separate class library, you will need to look in the Web.config and copy it over to your main application web.config. Also you will want to add the reference of it in your project references.
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.
i have changed the connection string to point to a database in the remote server. But when I execute the project the program still points to the local db.
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="TEDALS_Ver01.DAL.TedalsContext"
connectionString="Data Source=FE0VMC0643\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\TeDaLSdev.mdf;
Integrated Security=False"
providerName="System.Data.SqlClient"
/>
<!--<add
name="TEDALS_Ver01.DAL.TedalsContext"
connectionString="Server=FE0VMC0643; Database=TeDaLSdev; "
providerName="System.Data.SqlClient" />-->
<!--<add name="TEDALS_Ver01.DAL.TedalsContext"
providerName="System.Data.SqlClient"
connectionString="Server=FE0VMC0643;Data Source=FE0VMC0643;
Initial Catalog=TeDaLSdev;
Integrated Security=True;
Connect Timeout=15;
Encrypt=False;
TrustServerCertificate=False;" />-->
</connectionStrings>
Comments are the different connection strings i have treid so far. i never had a connections string when I was using the LocalDB.
Constructor for Connection
public class TedalsContext : DbContext
{
public TedalsContext()
: base("TedalsContext")
{
//Database.SetInitializer<TedalsContext>(null);
}
}
i am using SQL Server Express as my database. I have also tried changing the name of the parameter for base in constructor as the name of the Database. But it did not change anything.
I have already tried if I have access to the database through SSMS. I am able to create tables but I am unable to rename the database as such(I do not have access rights to rename the database TeDalSdev).
Are there any other work around i could try? Should the name of the remote database and the local database should be the same to avoid changing a lot of code?
UPDATE
Controller
public class LsystemFamiliesController : Controller
{
private TedalsContext db = new TedalsContext();
//Code goes here
}
I've added a connection string from a web config file of one of my projects and all the fields that (should) be checked. This is within the <connectionStrings> tags. You need to make it your default connection and you can only have one connection string as the default connection.
<add name="DefaultConnection" providerName="System.Data.SqlClient"
connectionString="Data Source=Providedbyhost;integrated
security=false;Initial Catalog=DB_Name;User Id=UserId;Password=password;
Trusted_Connection=false; TrustServerCertificate=true;
Encrypt=true;MultipleActiveResultSets=True" />
Where you have your DB Context:
public TedalsContext()
: base("DefaultConnection")
Switch everything to DefaultConnection, until you get it working, then you can focus on changing names. Comment out your local db connection strings. Even remove it from the project if you need to (and save it elsewhere), while you are testing this.
I've also added a screen shot of the my folder directory, to show which web config folder I am modifying. See it's highlighted in blue.
Also this screen shot shows you where to navigate to test your connection string within VS.
I suggest you look here:
How to: Access SQL Server Using Windows Integrated Security
What will be the connectionstring for mssql windows authentication
and this:
Connection string using Windows Authentication
As I suggested in the discussion. I recommend also contacting web hosting provider, as I have had this problem where it will not connect and it's been a problem at the hosting end.
If you need more help, shout out.
Under your TedalsContext constructor, use : base(connectionStringName).
Otherwise, the context will treat it as code first and create a TedalContext inside your SQLExpress Local DB.
public class TedalsContext : DbContext
{
public TedalsContext()
: base("TEDALS_Ver01.DAL.TedalsContext")
{
//Database.SetInitializer<TedalsContext>(null);
}
}
i registered my website on somee.com. for that i have uploaded MS SQL database. i was wrting this connection string in my code:
connectionString="metadata=res://*/nrcsaEntities.csdl|res://*/nrcsaEntities.ssdl|res://*/nrcsaEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=My-PC;initial catalog=nrcsa;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
now as i registered somee.com is providing me new connection string that is:
workstation id=nrcsadb.mssql.somee.com;packet size=4096;user id=DuaZoya_SQLLogin_1;pwd=abcd;data source=nrcsadb.mssql.somee.com;persist security info=False;initial catalog=nrcsadb
i have changed connectiong string in file web.config by replacing this first connection string with provided connection string by somee.com
PROBLEM:
This replacement is generating warning that:
System.ArgumentException: Keyword not supported: 'user id'.
how to solve this problem?
In the web.config file ....
<connectionStrings><add name="nameofConnection" connectionString="Data Source=servername; Initial Catalog=DatabaseName; User ID=UserName; Password=Password;"/> </connectionStrings>
<system.web>
<compilation debug="false" targetFramework="4.0" /> </system.web>
you can edit target Framework according to you.
from : http://dotnet-developers-cafe.blogspot.in/2013/08/create-connection-string-in-aspnet.html
You're using Entity Framework.
Entity Framework has its own connection string which contains a reference to the EF metadata (metadata=...) as well as the inner connection string to connect to the actual database.
You need to insert your actual database connection string inside the EF connection seting, in the provider connection string=... section.
You will also need to add multipleactiveresultsets=True to their connection string; EF needs that setting.
As you are using entity famework, then your connection string will look like
<connectionStrings>
<add name="BlogContext"
connectionString="metadata=res://*/BloggingModel.csdl|
res://*/BloggingModel.ssdl| res://*/BloggingModel.msl;
provider=System.Data.SqlClient
provider connection string="data source=[you somee.com connetion string];"" providerName="System.Data.EntityClient" />
</connectionStrings>
what you need to do is simply change the value of data source from the actual connectionstring provided by somee.com
Don't replace the whole connection string. You will need to remove the Integrated Security = true section and replace it with user=DuaZoya_SQLLogin_1;password=abcd.
Also change the data source to nrcsadb.mssql.somee.com.
You pretty much just need to replace values in your existing connection string with the values provided.