Autogenerated default connection string vs. manually added one - c#

Let's say I have got simple WPF application using Entity Framework Code First to create database, connect to it and display some data. From start I do not want to worry about connection strings so after adding entityframework reference via Nuget I'll get auto generated app.config looking like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
I'll run test and observe connection string:
var strings = ConfigurationManager.ConnectionStrings;
with result:
[0] = {data source=.\SQLEXPRESS;Integrated Security=SSPI;attachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true}
As I Like to define my own connection string, I will add this into my app.config:
<connectionStrings>
<add name="MyContext" connectionString="data ource=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
And so when I run the test again and observe the connection srings I can see that there are two now:
[0] = {data source=.\SQLEXPRESS;Integrated Security=SSPI;attachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true}
[1] = {data source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True}
Why is it that I can see two connection string? If the first one is default, should it not be forgoten once I've created one?
Thanks

First connection string which you see comes from machine.config from your PC. It has following section:
<connectionStrings>
<add name="LocalSqlServer"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Which defines default connection string for ASP.NET database. If you really don't need it for your application, you can either edit machine.config file (not recommended) or clear connection strings before adding yours:
<connectionStrings>
<clear />
<add name="MyContext"
connectionString="data source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Also keep in mind - this connection string is not used by Entity Framework. By default it uses SQLEXPRESS server and database with name equal to full name of your DbContext class. You can check it by accessing context.Database.Connection.ConnectionString.

The configuration manager just grabs all of the connection strings defined in the app/web.config.
It can't make the generalized assumption that once you add a connection string you wouldn't want a default one around anymore. That second connection string might point to an entirely different database.

Related

Multiple Groups of ConnectionStrings in App Config

Using ConnectionStrings in App.config, is it possible to have multiple groups/sections of connectionstrings? Some way to delineate between one set of connections and another. Either something like;
<configuration>
<connectionStrings>
<clear />
<add name="ConA" connectionString="Data Source=..."
<add name="ConB" connectionString="Data Source=..."
</connectionStrings>
<otherConnectionStrings>
<clear />
<add name="ConC" connectionString="Data Source=..."
<add name="ConD" connectionString="Data Source=..."
</otherConnectionStrings>
</configuration>
OR
<configuration>
<connectionStrings>
<clear />
<add name="ConA" Group="1" connectionString="Data Source=..."
<add name="ConB" Group="1" connectionString="Data Source=..."
<add name="ConC" Group="2" connectionString="Data Source=..."
<add name="ConD" Group="2" connectionString="Data Source=..."
</connectionStrings>
</configuration>
I know there are <configSections> which you can use to split up the config file, but I want to use ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings; to access the connectionStrings if possible.
NEED
I have two dropdown boxes. One is populated with a list of possible connectionStrings. Selecting an option will populate the second dropdown with a sublist of the remaining connectionStrings based on the option selected in dropdown 1. How would you cleanly populate both? Perhaps I'll just need to create connectionStringName lists in code for each group of connections I could potentially need and have all my connections in a the single section in my config?
Thanks for the comments. It seems having separate connectionStrings sections isn't possible. In order to hold onto that functionality for all my connections I conceded to having them all together but prefixing their names based on the grouping (as per #Igor's suggestion), then in code using Linq to select only the connections I needed.
Note: In order to use Linq on ConnectionStringSettingsCollection you need to .Cast<ConnectionStringSettings>() as per; https://stackoverflow.com/a/26419656/1365650

Windows Service unable to connect to DB with EF6

I developed a Windows Service, using Entity Framework 6.
I run the service, and when it tries to connect to database, it throws the following exception:
No connection string named 'testEntities' could be found in the application config file.
so i decided to change this code in test.Context.cs
public testEntities()
: base("name=testEntities")
{
}
into this:
public testEntities()
: base("data source=MyLocalServer/sqlexpress;initial catalog=test;persist security info=True;user id=xxxxxx;password=xxxxxxx;MultipleActiveResultSets=True;App=EntityFramework")
{
}
in practice i changed the name of the entity to the connection string. But it throws the following exception:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception.
If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection.
To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
in the solution there are 2 projects (including wix for creating installation package). The same error is thrown if i set my project as "StartUp Project"..
Add the following sections to your app.config file.
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="testEntities" connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.ssdl|res://*/Models.MyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=data source=MyLocalServer/sqlexpress;initial catalog=test;persist security info=True;user id=xxxxxx;password=xxxxxxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
/connectionStrings>
</configuration>
Where MyModel is the name of your database model.
Follow code
public testEntities()
: base("name=testEntities")
{
}
says that the connection string name in app.config is testEntities
Add connection string in app.config
<configuration>
...
<connectionStrings>
<add name="testEntities" connectionString="data source=MyLocalServer/sqlexpress;initial catalog=test;persist security info=True;user id=xxxxxx;password=xxxxxxx;" providerName="System.Data.EntityClient" />
...
I think it is better to add connection string to app.config
Add connectionstring in app.config
But If you want your solution . for get it to work
You should not set a default connection factory in app.config
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
So You must remove defaultConnectionFactory.
Have you checked the App.Config or Web.Config files? It is where the connection string is defined to connect the project with the database, make sure when you create the Code First to locate your server where the database is, this will edit the file and generate inside the connection string tag, which you can edit as you wish.

app.config: ConnectionString value not visible in project where it's defined

Hi I have a few projects in Solution.
In project A, I have app.config with connection string called Ver3ConnectionString. But when I do debug, the connection string is not found in code:). While debugging connection strings contains one which is not defined in this app.config, nether in my app :). Im using VS2013 Express :).
Moreover, applicationSettings are ones which are defined in main project:), but not one which is being dubugged.
Magic:).
ADDED:
THe solution was created by my coworker from existing project, so Im looking for error in solution/project files.
MobileWalletContext class is connected with EntityFramework 6.X. Maybe this is the problem?
Added 2:
This unknown connection string has name ="LocalSqlServer". Maybe this will be helpful?
App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="Ver3ConnectionString"
connectionString="Data Source=PAZI-PRO2\SQLEXPRESS;Initial Catalog=MobileWalletVer3;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
C# code where connsterionString is called:
public MobileWalletContext() : base(string.Format("name={0}",ConfigurationManager.ConnectionStrings["Ver3ConnectionString"].ConnectionString))
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MobileWalletContext>());
}
Name of the connection string is not likely to change. Therefore I would simplify context constructor to:
public MobileWalletContext() : base("Ver3ConnectionString")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MobileWalletContext>());
}
That way I could define different connection string in each project using Ver3ConnectionString name.
EDIT
DbContext base constructor accepts both connection string name or full connection string.
In your case instead of referencing existing connection string you are just creating a new connection string with provided name and default settings. Thats why you are seeing LocalSqlServer.
If you pass name of existing connection string in config, it will be picked up and used.
EDIT
Make sure your connection strings are in app.config or web.config file in your main project directory.
I'd like to add this to what #Kaspars-Ozols wrote:
LocalSqlServer is your SQL Express installation and its configuration usually resides in a machine.config file like C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config. You may have more than 1 machine.config [2 runtimes (2.0 and 4.0)] x [2 Bitness (x86 and x64)] makes 4 machine.config files!
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
It's a good habit to use <clear /> at the very beginning of <appSettings> or <connectionStrings> sections.
<connectionStrings>
<clear/>
<add name="MembershipConnection" connectionString="Server=.;UId=some_user;PWd=P#$$w0rd;Database=DBName" providerName="System.Data.SqlClient" />
<add name="ElmahConnection" connectionString="Server=.;UId=some_elmah_user;PWd=P#$$w0rd;Database=DBName" providerName="System.Data.SqlClient" />
</connectionStrings>

External database MVC 5.2.2 membership

I have been fighting for days with the new Google OAuth, and I believe I got it to work (removed and reinstalled owin), but now when I hit my site, I get:
SQLExpress database file auto-creation error:
...The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory...
Indicating that it is trying to access a SQL Express db in the App_Data directory. I want it to connect to my existing external SQL Server
I have created a connection strings (two now).
I have tried to changing the connection string passed into the base of ApplicationDbContext to my connection string:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("myconnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
I tried both pointing to a straight connection string, and an entity string. The entity string originally errored out about tables not being included, but now it is giving me the same error.
I have tried changing the web.config to:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="[tried a connection string here as well]"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
I have read hints like a line in FilterConfig.cs (that references a function that doesn't seem to exist in EF 5):
filters.Add(new InitializeMembershipAttribute());
I am just getting started with EF 5 coming from ASP.NET - The basic concepts are no issue, the framework is great and flexible, but Membership issues have been a beyond frustrating experience (and tiring that I've been at it this long)! I have created small sites in MVC without membership before...
Are there specific web.config entries that are missing, similar to those from the old school ASP.NET membership?
I am also using [Authorize(Roles = "a,b,etc")] - do I need to specify something specific for roles, or should the change to the identity class take care of it as well?
You need to add the connection string to your web.config. The base name set in the DbContext must match the name in the web.config and IS case sensitive.
Remote db looks like first line and local db looks like the second line.
Like this:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=0.0.0.0;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=someuser;Password=somepass" providerName="System.Data.SqlClient" />
<add name="mycontext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=mycontext-20150116012312; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|mycontext-20150116012312.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
... more content here ...
</configuration>
Hope this helps!

Changing connection string in app.config for Entity Framework

I am using Entity Framework. In app.config there is stored connection string that EF generates for my database.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="votemeEntities" connectionString="metadata=res://*/VoteModel.csdl|res://*/VoteModel.ssdl|res://*/VoteModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;User Id=root;database=voteme""
providerName="System.Data.EntityClient" />
<add name="VoteMe.Properties.Settings.votemeConnectionString"
connectionString="server=localhost;User Id=root;database=voteme"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
I need to set Charset in this connection string. How do I do it so my EF use this connection string without any problems?
Thanks
You can add the property at the end of the EF connection string, just before the ".
...abase=voteme;charset=UTF8;""
providerName="System.Data.EntityClient" />
Just make sure that the value is properly XML escaped (if needed), otherwise you will break the config file.

Categories

Resources