Entity Framework Connection String Trouble - c#

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'

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!

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

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);

EF 6.0 Code first Compact Edition: incorrect connection string or app.config problems?

ask your advices about this:
I am trying to create db compact edition,
first time it was successfully with default dbName (ProjectName.dbContextName).
But i decided to define my own name, and added in app.config in connectionString sections my connection string. After db was not created.
From here MSDN Use code first with connection by convention i have done similar connection string:
<connectionStrings>
<add name="TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
(section name is equal to my dbcontext's name class.)
Just to be sure before dbContext will be created:
Database.SetInitializer(new DropCreateDatabaseAlways<TestContext>());
Db still is not created. What am i doing wrong? Thanks in advance.
VahidN, i tried to add call of base class constructor, but doesn't work. Don't understand. It should be very easy. And as were aforementionted in ref above, if name of connection string in config section and name dbContext class are equal - object finds its connection string without problems.
Well, debugger says that conString is defined correctly (equal to string in config section), but actually db is not created - i can't find it nor in appfolder nor in sql server folders.
You need to include the full namespace in the name of the connection-string. See here.
Something like this
<connectionStrings>
<add name="YourNameSpace.TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
Oh, sorry me for giving insufficient information, db was not created cause entities in dbContext was defined as List, not dbSet. inadvertency (

Shared Connection Strings in Entity Framework

I want to create a single connectionString in my Web.config and then re-use it in the "provider connection string" attribute of all Modules declarations.
example :
Declare a connection string this way:
<add name="MyConnectionString" connectionString="Data Source=.;Initial
Catalog=MyDB;User ID=username;Password=pwd;" />
and then share this connection between modules:
<add name="Module1Context" connectionString="metadata=res//*/Module1.csdl| ... |
...;provider=System.Data.SqlClient;provider connection string=MyConnectionString"
providerName="System.Data.EntityClient" />
Is this possible?
It's not directly possible the way you have it described above.
The solution for this is almost certainly going to be FAR more work than just copying your connection strings, commenting or uncommenting entries as you go.
Be sure you are using Configuration Transformation files to manage this.
If you really must do this, then you will need to build the connection strings yourself, using the EntityConnectionStringBuilder class, pulling the provider connection string from your MyConnectionString value. Set the EntityConnection property in your context object when you instantiate it; see http://msdn.microsoft.com/en-us/library/bb896325.aspx for details.
You can manage your connection string in runtime using ConfigurationManager.ConnectionStrings
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx

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 "

Categories