is it possible to get the connection string to ADO from a connection string for entity framework? - ado.net

I have a connection string in my app config that is:
<connectionStrings>
<add name="MyEFConnection" connectionString="metadata=res://*/Model.AAA.csdl|res://*/Model.AAA.ssdl|res://*/Model.AAA.msl;provider=System.Data.SqlClient;provider connection string="data source=MyComputer\SQLEXPRESS;initial catalog=ABCD;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
But in a particular case I want to use ADO.NET to execute a T-SQL, so I using this code:
SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyEFConnection"].ConnectionString);
But I get an exception that says that the Metada word is not valid. There is any way to use the information in the connetion string for EF or I need to add a new string connection in my app config to the ADO.NET connection?
Thanks.

First you need to replace the & quot; with a single quot.
Then create an entity EntityConnection from your connection string:
EntityConnection entityConnection = new EntityConnection(connectionString);
And then you can get the connection string to ADO from the EntityConnection:
string ADOConnectionString = entityConnection.StoreConnection.ConnectionString;

Related

How to open a password protected SQL Server CE database with Entity Framework

I am using EF 6.0 and SQL Server CE 4.0. The .sdf file is password protected, which I verified by opening the file with LinqPad. When I try to open this database in code with the following connection string, I get an exception:
The specified password does not match the database password
Code:
using (var context = new MyDbContext("ExamManagement"))
{
context.Database.Initialize(false);
}
Connection string:
<connectionStrings>
<add name="ExamManagement"
connectionString="Data Source=|DataDirectory|Pikeman.sdf;Max Database Size=4091;Password=123;"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
Stack trace:
at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
at System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.b__5()
at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
The connection string is OK (usually I don't specify Max Database Size, you can try to delete the parameter but I'm quite sure this is not the problem).
So, in your case, I think you are probably opening a database with a different password (as the exception suggests) or you are opening a wrong database.
Try to specify an absolute path and open the database from that path, for example
<connectionStrings>
<add name="ExamManagement"
connectionString="Data Source=C:\temp\Pikeman.sdf;Password=123;"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>

How use EF on SqlConnection object

I have an old winforms project which uses localDB and ADO.NET SqlConnection. Now I have created a new database (not local), which I use Entity Framework to connect to. When I use the new EF-database on my SqlConnection I get the error that says SqlConnection does not support the metadata from my new connectionstring.
Is it correct that SqlConnection needs a localDB? How can I do so that the SqlConnection can connect to my new database?
//Martin
An Entity framework connection string contains a meta data element that points to the location of the entity framework model:
<connectionStrings>
<add name="AdventureWorksEntities"
connectionString="metadata=.\AdventureWorks.csdl|.\AdventureWorks.ssdl|.\AdventureWorks.msl;
provider=System.Data.SqlClient;provider connection string='Data Source=localhost;
Initial Catalog=AdventureWorks;Integrated Security=True;Connection Timeout=60;
multipleactiveresultsets=true'" providerName="System.Data.EntityClient" />
</connectionStrings>
A Sql connection string looks something like this:
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
If your application uses an SQLConnection then you must connect to the database with a connection string that has the structure of a SQLConnection string.

Entity Framework Code First Azure connection

I am using Entity Framework Code First 4.3 + Azure and having difficulties connecting to the database. The error I get is the following (on the first query):
Keyword not supported: 'server'.
I have the following connection set up in my Web.config
<configSections>
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<connectionStrings>
<add name="TestDBContext"
connectionString="Server=tcp:[SUBSCR].database.windows.net,1433;Database=[MyDB];User ID=[user];Password=[pass];Trusted_Connection=False;Encrypt=True;PersistSecurityInfo=True"
providerName="System.Data.EntityClient" />
</connectionStrings>
My DbContext implementing class uses the connection string's name:
public class MyContext : DbContext, IMyContext
{
public MyContext()
: base("TestDBContext")
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
}
Can you tell what is going on?
I just had the same problem.
You're missing all the metadata in the connection string that Entity Framework requires. The connection string provided by SQL Azure needs to inserted within the provider connection string parameter of EF's connection string.
<add name="MyConnectionString" connectionString="metadata=res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl;provider=System.Data.SqlClient;provider connection string="[PUT SQL AZURE CONN STRING HERE]"" providerName="System.Data.EntityClient" />
You'll need to use the metadata from your own project. I pulled that metadata from an EF project generating from an existing database.
I had the same problem. I solved, putting in the web.config this connectionstring:
<add name="eManagerTurModelConnection" connectionString="metadata=res://*/ORM.eManagerFinanceModel.csdl|res://*/ORM.eManagerFinanceModel.ssdl|res://*/ORM.eManagerFinanceModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=<server>.database.windows.net;Initial Catalog=eManagerTur;Integrated Security=False;User ID=<user>;Password=<Password>;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
And after I removed the connectionstring of my website, worked, because it was not getting the connection string that I added in my web.config.
English bad... =)
The provider should be providerName="System.Data.SqlClient"
I connected to Azure from VS and then looked at the properties and set my connection string and provider name.
<add name="context" connectionString="Data Source=myServer,myPort;Initial Catalog=myDBName;Persist Security Info=True;User ID=myUserName;Password=myPassword;" providerName="System.Data.SqlClient"/>
I was then able to run update-database with no issues.
i tried like this, it may help you. may be 1433 is making problem, is it port no ? or what? . try like this.
check this link Windows Azure with Sql
<add name="dbContext" connectionString="Server=tcp:xxxxxxxx.database.windows.net;Database=xxxxxxxx;User ID=xxxxxxx#xxxxxxxxx;Password=xxxxxxxxxx;Trusted_Connection=False;Encrypt=True;" providerName="System.Data.EntityClient" />
Try this:
Data Source=tcp:YOUR-DATABASE-HERE.database.windows.net,1433;
Database=GolfRounds;
User ID=YOUR-USERNAME#YOUR-SERVER; Password=YOUR-PASSWORD; Trusted_Connection=False; Encrypt=True;
There is also an MSDN article at http://msdn.microsoft.com/en-us/library/windowsazure/ff951633.aspx that may be helpful.
I had a similar problem where I did not have access to the metadata, in this case you need to use System.Data.SqlClient as the provider. You will also need to add MultipleActiveResultSets=True to your connection string

Is it possible to reference a connection string in another connection string?

We have a project with multiple DLLs. In each DLL, we connect to a database - always the same one for a client.
As a result, we now have 3 near-identical connection strings : one for our web site, one for ado.net, and one for telerik reporting :
<add name="BDConnectionString" connectionString="Data Source=localhost;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=PASSWORD; MultipleActiveResultSets=True;Pooling=True;Max Pool Size=500;" providerName="System.Data.SqlClient" />
<add name="CMS.Reporting.My.MySettings.BDConnectionString" connectionString="Data Source=localhost;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=PASSWORD" providerName="System.Data.SqlClient" />
<add name="KOPWebEntities" connectionString="metadata=res://*/Data.web.csdl|res://*/Data.web.ssdl|res://*/Data.web.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=PASSWORD;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
Now it's still manageable, but in the future, we will have more ADO.Net Entity Framework connections, so maybe 10 connection strings by client ?
Is there a way to say, "ok, for this connection string, use the value coming from here" instead of duplicating it ? At least for ADO.Net ?
Or is there a better way ?
Thanks
I noticed you mentioned Entity Framework. It is possible to create entity contexts with different SQL connections than the one defined in the application/web config. (I'd have to dig up the code). However, as far as the more general "have a connection string that actually references another connection string" question, I'd say, if you don't have the source, tough luck.
It'd probably be better if your DLLs didn't reference app/web config settings and, for the classes defined in there, you could pass in either the, the "application key" which has an associated value referencing a connection string, the SQL connection string itself, a SqlConnection instance, or some SqlConnection-Factory-Thing you make up.

EF CTP 4 Database name configuration

For sample I'm using this connection string :
<connectionStrings>
<add name="PicturesDatabase"
connectionString=" Server=.;
Database=SomeprojectDatabase;
Trusted_Connection=True;"
providerName="System.Data.SqlClient"/>
<../>
And then I use it in Application_Start() :
Database.DefaultConnectionFactory =
new SqlConnectionFactory(ConfigurationManager.
ConnectionStrings["PicturesDatabase"].ConnectionString);
And in my database I get this really strange new Database :
MyAppNamespace.Models.PicturesCatalog
with two tables dbo.EdmMetadata and dbo.Pictures
Tables are fine, but why doesn't it create a new database named PicturesDatabase (as in connection string) with those tables ?
I've tried dropping this table few times, I did try creating PicturesDatabase and using it... but it still generates this MyAppNamespace.Models.PicturesCatalog. What is the problem with it ? And how do I fix it ?
System.Data.Entity.Infrastructure.SqlConnectionFactory is not meant to use in this way. This connection factory includes a constructor that allows us to override pieces of the final connection sting, such as username, password and server and not the whole thing.
For example, we can change the Database Server like this:
Database.DefaultConnectionFactory =
new SqlConnectionFactory("Server=MyDatabaseServer");
What you try to do here can be easily accomplished by providing a connection string in your app.config that matches the name of your DbContext - I assume it's PicturesCatalog:
<connectionStrings>
<add name="PicturesCatalog" connectionString="data source=.;
Initial Catalog=PicturesDatabase; Trusted_Connection=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>