Entity Framework - Invalid Object with custom connections string - c#

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!

Related

Change connection string at runtime MySql C#

i have an app.config file that has a connection string for my database.
what i want to do is to connect to different databases that's why i used to this code:
connectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah";
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings[nameofConnectionString].ConnectionString = connectionString;
config.Save();
ConfigurationManager.RefreshSection(nameofConnectionString);
it works well, it changed the connection string, but the problem is that it sends me an error saying "facerec6.0.cdcol does not exist"
my default initial catalog = facerec6.0
what will i do ?
The ConnectionStringSection is just a container to store named connection strings. If you want to connect to different databases then it's best to start by storing those different connection strings in that section from the start and then determining how your application will choose which one to use at runtime.
Think of that section as just that and nothing more - it's a convenient, known place to store connection strings with a standard way to retrieve them. Other developers working on the code will know where to look for them and know how to retrieve them.
Even though it's technically possible to modify that section at runtime and save the file I wouldn't do that. If you have the same code that may use different connection strings while running in the same environment (it's not a case of one for development, one for QA, and one for production) then you could have your class depend on an interface something like this:
public interface IConnectionStringFactory
{
string GetConnectionString(Something key);
}
Where Something is a value that the class requiring the connection string can pass to the factory, and the factory can use it to determine which connection string to retrieve. That way the class that uses the connection string is insulated from that logic. It doesn't know why it uses one connection string or another. It just gets a connection string from the factory and then uses it.
If it's a case of varying connection strings by environment then that's much, much easier - you can do that with config transforms. In most cases if it's a different environment then all the connection strings will be different for each environment, so you can just replace the whole section.
<connectionStrings xdt:Transform="Replace">
<add name="connectionStringA" connectionString="...whatever..." />
</connectionStrings>
Please try this instead:
ConfigurationManager.RefreshSection("connectionStrings");
because:
<connectionStrings> <- this is the section
<add name="facerec6.0"/> <- this is the element
<add ... />
</connectionStrings>
You need to refresh the section, not the element, when using RefreshSection.

Can I use one connection string to use multiple databases with the same table structure in Entity Framework?

I have a web api application and it has its own database. The web api app distributes data to its branches' database. The branch databases are all same in table structure but each database has its own connection string in the web.config
<add name="Branch" connectionString="metadata=res://*/Models.HOGC.csdl|res://*/Models.HOGC.ssdl|res://*/Models.HOGC.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=GC_BranchName;user id=sa;password=Qwer0987;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="Branch_1" connectionString="metadata=res://*/Models.HOGC.csdl|res://*/Models.HOGC.ssdl|res://*/Models.HOGC.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=GC_BranchName_1;user id=sa;password=Qwer0987;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I am using Entity framework Database First and I route my data using dbcontext
public HOGCEntities(string connString)
: base("name=" + connString)
I have a list of branches in my main database table. It contains the name of the connection string and the name of the database/catalog (Branch_1 & GC_BranchName_1).
I want to know is, can I use just one connection string instead of manually or programmatically creating another connection string with the same attributes? Like looping through my branch table to route my data?
"How can I send postcards to several people living at different places by using the same address?"
Well, you can't.
The connection string is the "address" of a database and if you have several databases you need a specific connection string for each one of them.
However, if the databases have the same structure, you can use the same entity model and the same business classes for all of them.
Configuration settings
You can use the same connection string setting in your web.config, if you provide a template connection string with a placeholder for the catalog name:
<add name="Branch"
connectionString=
"...provider=...;data source=(local);initial catalog={0};..." providerName="..." />
where "{0}" is the placeholder.
public HOGCEntities(string catalog)
: base(String.Format(ConfigurationManager.ConnectionStrings["Branch"].ConnectionString,
catalog)
)
You will also need a reference to the assembly System.Configuration.dll and a using System.Configuration;.
Some databases allow you to create database links. By using them, you could link satellite databases to a master database. But this leads to the problem of accessing the different tables with the same name. I don't know how the same business class could be mapped to the different tables in turn.

Dynamic MySQL database connection for Entity Framework 6

I wish to pass a dynamic connection string to the entity framework context. I have over 150 schemas which are identical (one per account) and I would like to select the connection as such:
ApplicationDbContext db = new ApplicationDbContext("dbName");
In theory this would be fairly easy, as I can create a connectionString and pass it as the argument for the constructor, for example:
public ApplicationDbContext(string dbName) : base(GetConnectionString(dbName))
{
}
public static string GetConnectionString(string dbName)
{
// The connectionString passed is something like:
// Server=localhost;Database={0};Uid=username;Pwd=password
var connString = ConfigurationManager
.ConnectionStrings["MyDatabase"]
.ConnectionString
.ToString();
return String.Format(connString, dbName);
}
I can connect successfully when I just pass the connection string name, but not when I generate it dynamically as below. I realize now that it's because the connection string in web.config has the providerName="MySql.Data.MySqlClient" attribute in it.
When I pass the actual connection string dynamically to the connection though, it assumes that it needs to connect to SQL Server rather than MySQL and fails due to the connection string being invalid.
The question is, how do I pass the provider name to the connection string if I am creating it dynamically?
Entity Framework 6 offers some handy subtle changes which aid in both getting MySQL working and also creating dynamic database connections.
Getting MySQL working with Entity Framework 6
First, at the date of my answering this question, the only .Net connector drivers compatible with EF6 is the MySQL .Net Connectior 6.8.1 (Beta development version) which can be found at the official MySQL website here.
After installing, reference the following files from your Visual Studio solution:
Mysql.Data.dll
Mysql.Data.Entity.EF6.dll
You will also need to copy these files somewhere where they will be accessible to the project during build time, such as the bin directory.
Next, you need to add some items to your Web.config (or App.config if on desktop based) file.
A connection string:
<connectionStrings>
<add name="mysqlCon"
connectionString="Server=localhost;Database=dbName;Uid=username;Pwd=password"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
Also add the provider, inside the <entityFramework /> and <providers /> nodes, optionally (this is an absolute must in the second part of my answer, when dealing with dynamically defined databases) you may change the <defaultConnectionFactory /> node:
<entityFramework>
<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
</providers>
</entityFramework>
If you change the defaultConnectionFactory from the default sql server connection, don't forget to remove the <parameter> nodes which are nested in the defaultConnectionFactory node. The MysqlConnectionFactory does not take any parameters for its constructor and will fail if the parameters are still there.
At this stage, it's quite easy to connect to MySQL with Entity, you can just refer to the connectionString above by name. Note that if connecting by name, this will work even if the defaultConnectionFactory node still points at SQL Server (which it does by default).
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext() : base("mysqlCon")
{
}
}
The it is just a matter of connecting normally:
ApplicationDbContext db = ApplicationDbContext();
Connecting to a dynamically selected database name
At this point it's easy to connect to a database which we can pass as a parameter, but there's a few things we need to do.
Important Note
If you have not already, you MUST change the defaultConnectionFactory in Web.config if you wish to connect to MySQL
dynamically. Since we will be passing a connection string directly to
the context constructor, it will not know which provider to use and
will turn to its default connection factory unless specified in
web.config. See above on how to do that.
You could pass a connection string manually to the context like this:
public ApplicationDbContext() : base("Server:localhost;...")
{
}
But to make it a little bit easier, we can make a small change to the connection string we made above when setting up mySQL. Just add a placeholder as shown below:
<add name="mysqlCon" connectionString="Server=localhost;Database={0};Uid=username;Pwd=password" providerName="MySql.Data.MySqlClient" />
Now we can build a helper method and change the ApplicationDbContext class as shown below:
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(string dbName) : base(GetConnectionString(dbName))
{
}
public static string GetConnectionString(string dbName)
{
// Server=localhost;Database={0};Uid=username;Pwd=password
var connString =
ConfigurationManager.ConnectionStrings["mysqlCon"].ConnectionString.ToString();
return String.Format(connString, dbName);
}
}
If you are using database migrations, the following step is important
If you are using migrations, you will find that the ApplicationDbContext will be passed to your Seed method by the framework and it will fail because it will not be passing in the parameter we put in for the database name.
Add the following class to the bottom of your context class (or anywhere really) to solve that problem.
public class MigrationsContextFactory : IDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext Create()
{
return new ApplicationDbContext("developmentdb");
}
}
Your code-first migrations and seed methods will now target the developmentdb schema in your MySQL database.
Hope this helps someone :)
It's now 2019 of course things have changed a bit but Franciso's example really helped me on this. This is the simplest solution I could find and the only one that actually worked. I did change it a bit from what he has shown. Follow this to completion you should end up with a working solution.
I had to change a few things. I am going to be very explicit in what has to be done and I am going to use my actual file names etc so that you don't have to guess about substitutions. Many examples are also short on how to make it work at the end. This example has everything you need to know.
This was built on visual studio 2015 Entityframework 6 using MySql server 8.0.16.0.
Unfortunately the MySql connectors and libraries are a complete mess. The 8.0.xx.0 connector / net and MySql.Data.Entity.EF6 and MySql.Data are completely useless.
I have installed Connector Net 6.10.7.0, MySql.Data.Entity.EF6 6.10.7.0, and MySql.Data 6.10.7.0. That works for me and I will vigorously oppose changing this.
This is for MySql but I really don't know why it could not work for any db.
Scenario
I have a multi tenant situation where I have a common db and multiple tentant databases, one per customer The customer id is kept in the common db for login purposes and authorizaton and the customer id directs which database to use. The client db's are all called myclientdb_x where x is the client number. myclientdb_1, myclientdb_2, myclientdb_35 and so on.
I need to dynamically switch to whatever clientdb_x the code is currently serving. There is a initial database client called myclient_0 which is the template for all of the other myclient_x databases.
Step1
I created a specific connection string in my Web.config for this it looks like this. It allows connections to the clientdb_0
<add name="DefaultClientConnection" providerName="MySql.Data.MySqlClient"
connectionString="server=localhost;user id=xxx;
password=xxxx; persistsecurityinfo=True;database=clientdb_0" />
Step2
I created a new entity called ClientDbUserUpdater using the wizard. The data entity is called
ClientDbUserUpdater.edmx
I told it to use "DefaultClientConnection" as the DB connection
I told it to save this new connection string in the Web.config
This created new entity connection string in the Web.config file and it will look like
<add name="myclient_0Entities" connectionString="metadata=
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.csdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.ssdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.msl;
provider=MySql.Data.MySqlClient;provider connection string="
server=localhost;user id=xxxx;password=yyyyy;
persistsecurityinfo=True;database=myclient_0"" providerName="System.Data.EntityClient" />
You might have to dig a bit because the wizard is not good about putting in \n in appropriate places.
Notice that this connection string is fundamentally the same as the initial connection string except for its name and the fact that it has
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.csdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.ssdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.msl;
The res: strings are needed by the data entity and its why you can't just send a standard connection string into the data entity.
If you try to send in the initial connection string
<add name="DefaultClientConnection" providerName="MySql.Data.MySqlClient"
connectionString="server=localhost;user id=xxx;
password=xxxx; persistsecurityinfo=True;database=clientdb_0" />
you will get an exception from
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
Step3
This new connection string is the one you need to alter. I have not tested it but I am pretty sure if change the data entity model with the wizard you will need to make this change again.
Take string:
<add name="myclient_0Entities" connectionString="metadata=
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.csdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.ssdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.msl;
provider=MySql.Data.MySqlClient;provider connection string="
server=localhost;user id=xxxx;password=yyyyy;
persistsecurityinfo=True;database=myclient_0"" providerName="System.Data.EntityClient" />
and change it to:
<add name="myclient_0Entities" connectionString="metadata=
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.csdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.ssdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.msl;
provider=MySql.Data.MySqlClient;provider connection string="
server=localhost;user id=xxxx;password=yyyyy;
persistsecurityinfo=True;database={0}"" providerName="System.Data.EntityClient" />
Notice that the only part changed is database=myclient_0 to database={0}
Step 4
The data entity created some code behind ClientDbUserUpdater.edmx. The file is called ClientDbUserUpdater.Context.cs.
The code is ...
namespace what.ever.your.namespace.is
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class client_0Entities : DbContext
{
public client_0Entities()
: base("name=client_0Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<user> users { get; set; }
}
}
Notice that this a partial class. This means you can extend this class and add a new constructor.
Add the following class.
using System;
using System.Configuration ;
using System.Data.Entity ;
namespace what.ever.your.namespace.is
{
public partial class client_0Entities : DbContext
{
public client_0Entities(string dbName) : base(GetConnectionString(dbName))
{
}
public static string GetConnectionString(string dbName)
{
var connString = ConfigurationManager.ConnectionStrings["client_0Entities"].ConnectionString.ToString();
// obviously the next 2 lines could be done as one but creating and
// filling a string is better for debugging. You can see what happened
// by looking a conn
// return String.Format(connString, dbName);
string conn = String.Format(connString, dbName);
return conn ;
}
}
}
The class adds a new constructor which allows you to get the base connection string for the data entity model which from above looks like:
<add name="myclient_0Entities" connectionString="metadata=
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.csdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.ssdl|
res://*/Areas.Authorizations.Models.ClientDbUserUpdater.msl;
provider=MySql.Data.MySqlClient;provider connection string="
server=localhost;user id=xxxx;password=yyyyy;
persistsecurityinfo=True;database={0}"" providerName="System.Data.EntityClient" />
and modfiy it at run time to change the schema.
The String.Format() call in the new partial class swaps out the database schema name in this connection string at run time.
At this point all configuration is done.
Step 5
Now you can make it go. For better understanding of this example it is nice to know what the model looks like for this entity. It is very simple because I was just testing and trying to make it go.
Drilling down through ClientDbUserUpdater.edmx and into into ClientDbUserUpdater.tt you will find your model in modelname.cs . My model is called "user" so my file name is called user.cs
namespace what.ever.your.namespace.is
{
using System;
using System.Collections.Generic;
public partial class user
{
public int UserId { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<bool> Active { get; set; }
}
}
Now you can generally access your model like this.
client_0Entities _client_0Entities = new client_0Entities("schemaName");
and this code can be anywhere in your solution that can see class client_0Entities.
which in practice is a line similar to any of the 3 below which are connection to databases client_19, client_47 and client_68 respectively.
client_0Entities _client_0Entities = new client_0Entities("client_19");
client_0Entities _client_0Entities = new client_0Entities("client_47");
client_0Entities _client_0Entities = new client_0Entities("client_68");
the following is an actual code example that works on my system. Obviously I am going to not hard code in "client_19" but its better for demo purposes.
here is actual code with real names that works and adds a new row to the user table on database client_19
string _newSchema = "client_19"
using(client_0Entities _client_0Entities = new client_0Entities(_newSchema))
{
user _user = new user();
_user.UserId = 201;
_user.Email = "someone#someplace.com"
_user.FirstName ' "Someone";
_user.LastName = "New";
_user.Active = true;
client_0Entities.users.Add ( _user ) ;
client_0Entities.SaveChangesAsync ( ) ;
}
Hopefully this helps some people. I spent about 20 hrs looking at different solutions which simply did not work or provide enough information to complete them. As I said, finding Franciso's example allowed me to get it working.
Regards,

In An Asp.net MVC Pgroject Use Entity Framework to Connect different Oracle TableSpace

As the title , I had try to solve an Asp.net Problem that I have Using asp.net mvc and Entity Framework 4.1 in my project , and now I want to use EF to connect different TableSpace in Just only one oracle instance , but now I have a problem that I didn't kown how to use Entity Framework to Connection Different TableSpace in an oracle instance in an MultiTenancy Asp.Net MVC Project , I had tried to config multiple ConnectionString in Web.config file ,and they have different username and password to connect different oracle tablespace ,just like below:
ConnectionString "MyDBModel1"
<add name="MyDBModel1" connectionString="metadata=res://*/EntityModels.MyDBModel1.csdl|res://*/EntityModels.MyDBModel1.csdl.ssdl|res://*/EntityModels.MyDBModel1.msl;provider=Oracle.DataAccess.Client;provider connection string="DATA SOURCE=ORCL;PASSWORD=123456;PERSIST SECURITY INFO=True;USER ID=MyDBModel1"" providerName="System.Data.EntityClient" />
ConnectioString "MyDBModel2"
<add name="MyDBModel2" connectionString="metadata=res://*/EntityModels.MyDBModel2.csdl|res://*/EntityModels.MyDBModel2.csdl.ssdl|res://*/EntityModels.MyDBModel2.msl;provider=Oracle.DataAccess.Client;provider connection string="DATA SOURCE=ORCL;PASSWORD=123456;PERSIST SECURITY INFO=True;USER ID=MyDBModel2"" providerName="System.Data.EntityClient" />
but the EF DataModel already had specific configuration key name ,just like
/// <summary>
/// Initalize New MyDBModel1 Object
/// </summary>
public MyDBModel1() : base("name=MyDBModel1", "MyDBModel1")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
As we have seen,it had assign the ConnectionString key name is "MyDBModel1", and here I have not find a way to use the ConnectString that name is "MyDBModel2" at the same time .This is All My Question , Maybe I think it is not very clear when I ask describe this question ,and thanks for you help .
From your question I understand the requirement of accessing different table spaces. There is no mention on either you want to achieve this for a single user or under which context. However I am suggesting the following.
1. You identify the context under which you will have to switch the table spaces. Like each tenant has his own table space.
2. You have an option of passing the EntityConnection as a parameter when you initialize your ccontextbin your data access logic.
3. Based on your identification of the user /tenant, you will have to pass in the connection string in the EntityConnection object. This way you can switch between different connection strings at run time. The point is the identification of the table space and the user / tenant association.

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