CodeFirst:The specified named connection is either not found in the configuration - c#

I create a Test Project to test my queries , every thing goes okay except when i try to test a method which use Entity Connection ,I get the following exception :
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
My connection string in app.config in the TestQuery Project which is my startup project is:
<connectionStrings>
<add name="DataLayer.Context" connectionString="Data Source=.;Initial Catalog=TestQ;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
All the methods which use linq to entity works just fine and brings the data except this one ?

This is not the way to execute an Entity SQL command. You should do this instead:
// If you have a DbContext instance:
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
var query = objectContext.CreateQuery<Crop>(eSQL);
var result = query.ToList();

Try to rename you connection name, in instance to this: "TestConn"
using(var con = new EntityConnection("name=TestConn"))
Another thing to try is to obtain you connection string from app.config and then to pass it in the constructor of EntityConnection.
string cs = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString
var eConnection = new EntityConnection(cs);

Related

Entity Framework - Invalid Object with custom connections string

Just for a brief overview this is how I added the database into my project:
I have added a datasource by adding an ADO.NET Data Model Entity and selecting EF Designer from Database.
Doing so has generated a connection string for me in my web.config. Integrated Security is set to true (if that matters).
Once connected I right clicked and selected 'Update model from database.
Since there is multiple environments I built a custom context with a parametized constructor. Code looks as such (condensed and censored):
public partial class DataEntities : DbContext
{
public DataEntities(string connectionString)
: base(connectionString)
{
}
}
With each environment there are different local sql accounts associated. Requiring me to generate a connection string that is associated with the correct account in the correct environment. Doing so my web config looks something like this:
<connectionStrings>
<add name="DataEntities" connectionString="metadata=res://*/Models.XXModel.XXModel.csdl|res://*/Models.XXModel.XXModel.ssdl|res://*/Models.XXModel.XXModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MYSQLSERVER;initial catalog=Data;integrated security=True;MultipleActiveResultSets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<secureConnectionStringsSection passwordPolicy="AllowLocalPasswordsForConnectionStrings">
<secureConnectionStrings>
<add name="DataEntities-Local" providerName="System.Data.SqlClient" connectionString="data source=MYSQLSERVER;user id=ACCNT; password=PASSWORD;" />
</secureConnectionStrings>
</secureConnectionStringsSection>
When I am instantiating my DataEntity object, I am calling a helper function I have written to get my custom connection string. I am doing so via the following code:
private DataEntities adDB = new DataEntities(XXX.Helpers.EFDBHelper.getDataConnectionString());
I can verify that my connection string helper does correctly pull the custom connection string that I have in my web.config. However once I actually try to make a call on the database I am left with the following error:
Invalid object name 'dbo.mycolumn'.
I know that my parametized constructor is being called with the correct connection string. I also know my connection string is valid, I have tested it in powershell:
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "data source=MYSQLSERVER;user id=ACCNT;password=PASSWORD"
$conn.Open()
$conn.Close()
I am certain that it is not an issue with the database itself as well. The moment I remove the parameter from my Entity initialization:
private DataEntities adDB = new DataEntities();
I am able to pull data from the database. I am assuming that it uses the auto-generated connection string. Which won't work since I cannot use integrated security once it goes past my local environment.
My apologies, I am new to the technology here. I am sure that it is just something small that I am missing.
In my connection string I did not specify a catalog.
Since I am newish to the technology, I tried to simply replicate some of the existing code that I had inherited. In the connection string I tried to replicate from, no catalog was expressed as well.
However... the account I am using to talk to the new datasource has access to all levels of the database so the catalog was required. The old inherited database had only one catalog the the sql account had access too.
You live and you learn!

Connection string was not found

I am trying to run this code:
var db = Database.Open("DBNAME");
var q = "Select Name From Table";
#foreach(var row in db.Query(q)){
<li> #row.Name </li>
}
But I get the error System.InvalidOperationException: Connection string "DBNAME" was not found.
So I went in to WebMatrix 3 and added this database under Other Connections and working fine in the WebMatrix3 app. But the connection string I fed WebMatrix to add to the connections was not appended to the web.config file, and I still get this error, so not sure what else to do? Suggestions?
Also, do DB connections like this have to be closed? I did not see a close statement in the example I took this from, which is from here: http://www.w3schools.com/aspnet/webpages_database.asp
Update: I added the following setting in web.config:
<connectionStrings>
<add name="DBNAME" connectionString="server=(local)\Server;database=DBNAME;uid=myUser;password=myPass;" />
</connectionStrings>
And now I get the following error instead: System.ArgumentException: Keyword not supported: 'server'. <-- this error shows up for the #foreach line
You can just add the connection string to your web.config file. Depending on what kind of database you use.
If you use SQL Server you can use something like this:
<configuration>
<connectionStrings>
<add name="DBNAME" connectionString="Data Source=.\Server;Initial Catalog=MyDatabase;User ID=Username;Password=Password" providerName="System.Data.SqlClient"/>
</connectionStrings>
<configuration>
More on connection strings here: http://www.connectionstrings.com/
Edit:
Yes Database connection should be closed! It implements IDisposable interface so you should use the using clause.
Here is an example
using (Database db = Database.Open("DBNAME"))
{
// Do your database stuff here
}
It will call the Dispose mehtod when it reaches the end of using clause. Dispose() will close the connection upon many other things.

Changing LINQ-to-SQL connection string at runtime

An application of mine uses LINQ-to-SQL extensively, and it is now a requirement of the application to be able to switch which database it is looking at at runtime - so essentially I would like to be able to choose the connection string of my data context when I declare it.
Is there an easy way of doing this?
Just call :
DataContext context = new DataContext ("cxstring");
You could use an App.config to store your Connection Strings then use them to populate a drop down box or something. Then use the selected Connection string in the constructor of your LINQ2SQL data context.
App Config:
<configuration>
<connectionStrings>
<add key="ConString1" connectionString="ConnectionStringGoesHere"/>
<add key="ConString2" connectionString="ConnectionStringGoesHere"/>
</connectionStrings>
Use the ConfigurationManager class to access your connection strings.
string conString = ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;
You can also enumerate over them or set them as datasource to populate a drop down box.
Then simply pass the selected string in as the first parameter in your LINQ2SQL datacontext constructor.
MyModelDataContext context = new MyModelDataContext(selectedConString);
If you mean by switching which database your application is looking at ,Test database and production database , simply you can make two connection string in your web.config file with the same key but has different connection string and comment one of them according to the desired database
<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=ProductionDB;" providerName="System.Data.SqlClient" />
<!--<add name="MyConnectioString" connectionString="Data Source=myServer;Initial Catalog=TestDB;" providerName="System.Data.SqlClient" />-->
by comment and uncomment you can switch between the 2 databases in run time.
to choose the connection string of your context provide it with its constructor
DataContext Productioncontext = new DataContext ("MyConnectioString");

specified named connection is either not found or Format of the initialization string does not conform to specification starting at index 0.

What does this error mean?
Format of the initialization string does not conform to specification starting at index 0.
and also getting this error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
I'm trying to use my EF model context in another project in Visual Studio. Having real trouble just getting my EF application off the ground.
I instantiate the model context like so:
ctx = new VisitoriDataModel("VisitoriDataModel");
I have the connection string copied from the data layer project into all projects including the web.config and still no luck.
Also tried the following:
//model = new VisitoriDataModel(new EntityConnection("Name=VisitoriDataModel"));
//model = new VisitoriDataModel("Name=VisitoriDataModel");
//model = new VisitoriDataModel("VisitoriDataModel");
//model = new VisitoriDataModel();
ConnectionString is like so:
metadata=res://*/Context.VisitoriDataModel.csdl|res://*/Context.VisitoriDataModel.ssdl|res://*/Context.VisitoriDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=visitori;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"
The connection string needs to go in the project that is being executed. If this is a website, that would be the web.config. Make sure it's correctly nested, and not inside another node like <system.web>, you should have:
<configuration>
...
<connectionStrings>
<add name="VisitoriDataModel" connectionString="metadata=res://*/Context.VisitoriDataModel.csdl|res://*/Context.VisitoriDataModel.ssdl|res://*/Context.VisitoriDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=visitori;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
...
</configuration>
Also note that the "'s around the provider connection string inside the entity connection string need to be escaped as "

Entity Framework Connection String Trouble

I am making a little library(DLL) to manage users and their roles/privileges. The plan is to be able to add this dll to an MVC project and be able to manipulate users/roles/etc. All the data resides in a SQL db.
I am using entity framework for data access.
So when I initialize a new RoleManager(this is the name of the main class in the lib I'm making) I supply it with a connectionString like so:
RoleManager roleManager = new RoleManager(string connectionString);
Then inside the constructor I do this:
db = new RoleManagerEntities(connectionString); //This is the EntityFramework
And I am trying to supply this connection string (among many others)
"metadata=res://*/RoleManager.csdl|res://*/RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'"
And I get the following error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
This question is a result of having trying to instantiate the EF from my new project without supplying a connection string and without having anything inside my app config for it to default to. Too bad I can't delete it now.
Just copy the connection string information from your DLL config file to your executable config file.
Basically you are trying to instantiate an ObjectContext via this ObjectContext Constructor (String) without passing the string parameter in its expected format and that's the problem.
Here is what you need to do:
1. First create an entry in your in your "test project" app.config because that is the place that the CLR is looking at to find the connection string at runtime.
<configuration>
<connectionStrings>
<add name="RoleManagerEntities" connectionString="metadata=res:///RoleManager.csdl|res:///RoleManager.ssdl|res://*/RoleManager.msl;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'" />
</connectionStrings>
</configuration>
2. Now change the code to pass the connection string name instead of the actual connection string:
db = new RoleManagerEntities("name=RoleManagerEntities");
The constructor might be looking for a connection string in the connectionStrings setting of your web.config with the name that you pass it as the parameter.
So if you call:
db = new RoleManagerEntities("Foobar");
It is looking for:
I'm not positive that this is the solution but that's what the error message seems to indicate.
I am not an expert on EF, but I don't think that connection string is valid. Try:
metadata=res://*;provider=System.Data.SqlClient;provider connection string='Data Source=localhost;Initial Catalog=Login;Integrated Security=True;Connection Timeout=60; multipleactiveresultsets=true'

Categories