Entity Framework - The underlying provider failed on ConnectionString - c#

While using the Entity Framework I have split it out to it's own project:
RivWorks.Model - Contains Entity Model
RivWorks.Controller - Uses the Entity Model and contains the biz rules
RivWorks.View.Web - The web site
RivWorks.View.Services - WCF project
Everything in the web site is working fine. I am able to call into the Controller and get a valid Model back. When I try the same thing from the Web.Service I am getting this error:
ERROR:
The underlying provider failed on ConnectionString.
STACK TRACE:
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString)
at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
at RivWorks.Model.Entities.RivFeedsEntities1..ctor(String connectionString)
at RivWorks.Model.FeedStoreReadOnly..ctor(String connectionString)
at RivWorks.Controller.ProductManager.LookupProduct(String productID, String sku, String urlRef, String env, String logPath)
I am a bit confused as to why and digging through the error logs I finally figured out the connection strings were not being read from the Web Site's config file. So, I added some code to catch that and, for now, hard coded the values in. Like:
public dataObjects.NegotiateSetup LookupProduct(string productID, string sku, string urlRef, string env, string logPath)
{
string feedConnString = "";
string rivConnString = "";
log.InitializeLogFile(logPath);
dataObjects.NegotiateSetup resultSet = new dataObjects.NegotiateSetup();
try { feedConnString = AppSettings.FeedAutosEntities_connString; }
catch { feedConnString = #"metadata=res://*/Entities.FeedEntities.csdl|res://*/Entities.FeedEntities.ssdl|res://*/Entities.FeedEntities.msl;provider=System.Data.SqlClient;provider connection string='Data Source=***.***.***.***;Initial Catalog=******;Persist Security Info=True;User ID=******;Password="******";MultipleActiveResultSets=True'"; }
try { rivConnString = AppSettings.RivWorkEntities_connString; }
catch { rivConnString = #"metadata=res://*/Entities.RivEntities.csdl|res://*/Entities.RivEntities.ssdl|res://*/Entities.RivEntities.msl;provider=System.Data.SqlClient;provider connection string='Data Source=******;Initial Catalog=******_Dev;Persist Security Info=True;User ID=******;Password="******";MultipleActiveResultSets=True'"; }
try
{
using (RivFeedsEntities1 _dbFeed = new FeedStoreReadOnly(feedConnString).ReadOnlyEntities())
{
using (RivEntities _dbRiv = new RivWorksStore(rivConnString).NegotiationEntities())
{
But, alas, it is still giving me the above error! Any ideas why?

I know you've been mucking around with your connection strings to sanitize them but I'm guessing you didn't put the "'s around the password in?
Are they actually required?

Double check your connection string is correct, little typo's can cause this same error.
This is wrong:
<add name="Entities" connectionString="metadata=res://*/OnlineAB.csdl|res://*/OnlineAB.ssdl|res://*/OnlineABSuperAdmin.msl;provider=System.Data.SqlClient;provider connection string="data source.;initial catalog=
This is right:
<add name="Entities" connectionString="metadata=res://*/OnlineAB.csdl|res://*/OnlineAB.ssdl|res://*/OnlineABSuperAdmin.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=
See after the DataSource I was missing an equal sign.

Related

How to put string as connection string to app.config?

I want to put my connection string on a USB dongle lock and make my app to read connection string from the lock.
But I don't know how to pass the string to ado.net and the connection string placed on app.config.(I'm using ado.net)The following code is my connection string tag:
<connectionStrings><add name="Db_ReceptionEntities1" connectionString="metadata=res://*/Model.DBReception.csdl|res://*/Model.DBReception.ssdl|res://*/Model.DBReception.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Db_Reception;user id=sa;password=******;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
How to put string as connection string to app.config?
You do not need to read from the dongle and put it into app.config. You can just read from the dongle and give the connection string to your context.
Your connection string looks like an EF database first connection string. The DbContext class has a constructor which accepts a connection string name or a full connection string. You can use that and pass the connection string to it.
Create your context like this:
public class StackContext : DbContext
{
public StackContext(string connection) : base(connection)
{
}
}
Then read the connection string from the dongle and pass it to your context like this:
// read from dongle
var connectionString = ...;
var ctx = new StackContext(connectionString);
this helped:
public Db_ReceptionEntities1(string x)
: base("name=Db_ReceptionEntities1")
{
Database.Connection.ConnectionString = x;
}

Changing the EF connection string gives - Keyword not supported: 'metadata'

For the past few hours I've been looking into this problem, found many similar topics but none of them seems to help.
I have a C# application that uses the Entity Framework 5 and I have a .edmx data model that works fine when using the connection string from the app config file.
Now I would like to change the connection string during runtime, but it throws an exception that says:
Keyword not supported: 'metadata'.
Here is the code that I have:
private string GetNewConnectionString(string server, string database, string username, string password)
{
var sqlBuilder = new SqlConnectionStringBuilder()
{
DataSource = server,
InitialCatalog = database,
UserID = username,
Password = password,
IntegratedSecurity = true,
MultipleActiveResultSets = true
};
var entityBuilder = new EntityConnectionStringBuilder()
{
Provider = "System.Data.SqlClient",
ProviderConnectionString = sqlBuilder.ToString(),
Metadata = "res://*/MyTestModel.MyTestModel.csdl|res://*/MyTestModel.MyTestModel.ssdl|res://*/MyTestModel.MyTestModel.msl"
};
return entityBuilder.ToString();
}
public void insertInDB()
{
var newConnectionString = GetNewConnectionString(server, database, username, password);
//newConnectionString = newConnectionString .Replace("\"", """); // doesn't help
//newConnectionString = newConnectionString .Replace("\"", "'"); // doesn't help either
using (var context = new MyTestModel.MyEntities(newConnectionString)) // it crashes here
{
}
}
The metadata should be correct, because I have copied it from the app config file, also if I copy the value of newConnectionString to the app config and use it, it works fine if I replace the quotations with ".
This is the value of newConnectionString (i've only replaced the credentials with some dummy credentials):
metadata=res:///MyTestModel.MyTestModel.csdl|res:///MyTestModel.MyTestModel.ssdl|res://*/MyTestModel.MyTestModel.msl;provider=System.Data.SqlClient;provider
connection string="Data Source=myServer;Initial
Catalog=myDatabase;Integrated Security=True;User
ID=myDbUser;Password=myDbUserPassword;MultipleActiveResultSets=True"
I cannot see what is wrong with it, can anybody spot something?
This answer: Entity Framework change connection at runtime solves the problem
I cannot understand what the problem with my code was, but it works fine with the extension method from the link.

Setup a valid connection string for SimpleMembership

I am trying to setup a valid connection string for my database so that my WebSecurity.InitializeDatabaseConnection method can point to my database.
Here's my connection string:
<add name="Database_Entities1" connectionString="metadata=res://*/Models.DAL.Entities.MTG_Model.csdl|res://*/Models.DAL.Entities.MTG_Model.ssdl|res://*/Models.DAL.Entities.MTG_Model.msl;provider=System.Data.SqlClient;provider connection string="data source=**.**.***.***;initial catalog=Model_Name;persist security info=True;user id=*****;password=*********;multipleactiveresultsets=True;application name=EntityFramework;Pooling=True;Max Pool Size=1000"" providerName="System.Data.EntityClient" />
The problem here is the provider name which is System.Data.EntityClient. I actually need it to point toward System.Data.SqlClient, but when I try to copy/paste the connection string and replace the System.Data.EntityClient with the other provider name, I get such crash like Keyword not supported: 'metadata'..
So my understanding is that calling my method like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext _filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<Database_Entities1>(null);
try
{
using (var context = new Database_Entities1())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("Database_Entities2", "UserProfile", "UserId", "UserName", true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
Where Database_Entities2 is:
<add name="Database_Entities2" connectionString="metadata=res://*/Models.DAL.Entities.MTG_Model.csdl|res://*/Models.DAL.Entities.MTG_Model.ssdl|res://*/Models.DAL.Entities.MTG_Model.msl;provider=System.Data.SqlClient;provider connection string="data source=**.**.***.***;initial catalog=Model_Name;persist security info=True;user id=*****;password=*********;multipleactiveresultsets=True;application name=EntityFramework;Pooling=True;Max Pool Size=1000"" providerName="System.Data.SqlClient" />
Does not work because an SqlClient connection string does not work that way. Can anyone help me achive what I'm trying to do? Thanks a lot!
EDIT
Two additionnal piece of information: I have this connection string:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MyApp-20130829080410;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MyApp-20130829080410.mdf" providerName="System.Data.SqlClient" />
Which was working; however, as you can see, it does not point toward my database, so if I try to retrieve any users in the table "UserProfile", it is not possible since the table was created in the local database (which I don't know why I have), and not in the main one (Database_Entities1), hence this question.
The SimpleMembershipProvider expects a normal connection string, not an entity framework connection string. You need to define a separate connection string that points to the same database as your entity framework connection string and use that:
<add name="MembershipDB"
connectionString="Data Source=**.**.***.***;Initial Catalog=Model_Name;[...]"
providerName="System.Data.SqlClient" />
If you use Entity Framework the connection string would be created by the IDE. And from your description i guess you created that connection string by your own, not via IDE.
So the IDE would place something like this in your app.config:
<add name="libraryEntities1" connectionString="metadata=res://*/privlibDBmodel.csdl|res://*/privlibDBmodel.ssdl|res://*/privlibDBmodel.msl;provider=System.Data.SqlClient;provider connection string="data source=[yourserver];initial catalog=library;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
To create the connection in your program you could use this:
libraryEntities1 dbconn = new libraryEnitits1();
Now you could handle the connections via dbcon object.

Set Entity Framework Connection String at Runtime in C#

I need to set my Entity Framework connection string at runtime. Right now, I have the following:
string connectionString = "metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework"";
using (CustomerEntities entities = new CustomerEntities(connectionString))
{
CustomerEntity entity = new CustomerEntity();
// do more
entities.CustomerEntities.Add(entity);
entities.SaveChanges();
}
When I execute the code above (with the {parameter} values replaced), I get the following error:
Keyword not supported: 'data source'.
What am I doing wrong?
Change this.
string connectionString = "metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework"";
To this (note how i escaped the " character as "" )
string connectionString = #"metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string= ""data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework""";
I know this was asked 10 months ago, but I found an easier way to specify the connectionString:
If your config file has it as:
<connectionStrings>
<add name="CustomerDataModel" connectionString="metadata=res://*/EntityFramework.CustomerDataModel.csdl|res://*/EntityFramework.CustomerDataModel.ssdl|res://*/EntityFramework.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\CustomerDataModel;initial catalog=CustomerDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
You can specify it as -
public const string ConnectionString = #"name=CustomerDataModel";
..
CustomerDBContext context = new CustomerDBContext(ConnectionString );
No need to worry about quotes. Lot cleaner.
It is easier to use EntityConnectionStringBuilder and SqlConnectionStringBuilder to change parameters as you want.
set multiple connection strings in your web.config, and follow below:
public partial class MyDatabaseEntities
{
public MyDatabaseEntities(string connection)
: base(connection)
{
}
}
and then wherever you want to create instance of entities, pass connection string name in parameter:
MyDatabaseEntities entities = new MyDatabaseEntities("CONNECTION_STRING_NAME");
I hope this will help.
Thanks

SQL Server connection string in code vs config file in ASP.NET site

I already have a connection string in my config file
<connectionStrings>
<add
name="ConnectionString"
connectionString="Data Source=*;Initial Catalog=*;User ID=*;Password=*"
providerName=".NET Framework Data Provider for SQL Server" />
Currently I am just adding another connection string in my .cs file:
SqlConnection myConnection =
new SqlConnection("user id=*;password=*;server=localhost;");
I want to use config file string to connect to a database in the .cs file without adding another string. How can I do that?
using (SqlConnection cn =
new SqlConnection(
ConfigurationManager.ConnectionStrings["MyDbConn"].ToString()))
This was the code I found, is there any shorter way?
Using ConnectionStrings property of System.Web.Configuration.WebConfigurationManager to get connection string in config file
Not really, but you could wrap it in its own little helper function:
private static string GetConnectionString(string name)
{
return WebConfigurationManager.ConnectionStrings[name].ConnectionString;
}
using (var cn = new SqlConnection(GetConnectionString("MyDbConn"))) { ... }
Just use System.Configuration.ConfigurationManager.ConnectionStrings to get access to the connection string defined in your config file.
var myconnectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
You can create a static helper class, named Config or something similar and give it a property ConnectionString, that will return the long "WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString" thing. That is the approach I usually go with in my projects and it's actually very easy to use.
public static class Config
{
public static string ConnectionString
{
get
{
return WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString;
}
}
}
This approach is the most useful when more classes need to acccess the connection string and this way you have a centralized access to it and easy to change solution.

Categories

Resources