Windows Service unable to connect to DB with EF6 - c#

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.

Related

How to handle "No connection string named 'RestaurentEntities' could be found in the application config file" in WinForms

I am trying a project on WinForms. I made a Form name Dashboard and User Control name DashboardScreen.
Dashboard basically will have many User Controls on it like DashboardScreen, InventoryScreen, SettingsScreen etc. These screens are small and Dock in main parent form Dashboard so when user click on button, corresponding user control comes to the front using DashboardScreen.BringToFront()
These user controls are implementing Entity Framework V 6.4.0 User controls and Main Dashboard Form works fine when I do not use Entity Framework on these controls. Whenever I use Entity Framework as RestaurentEntities DB = new RestaurentEntities(); to utilize database services the Main Dashboard Form gives the following Error in Design Mode.
No connection string named 'RestaurentEntities' could be found in the application config file.
Second Error is
The variable 'dashboardScreen' is either undeclared or was never assigned.
Given is my configuration file.
<?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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<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>
<connectionStrings><add name="RestaurentEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=YASIR\SQLDEVENV;initial catalog=Restaurent;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
if you want to drag and drop a UserControl in a form and the control in the constructor method or OnLoad method has access to EntityFramework and the EntityFramework access is created by referenced project you must include into your code something like:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!DesignMode)
{
//access to EntityFramework
}
}
Change your connectionStrings to below:
<connectionStrings>
<add name="RestaurentEntities"
connectionString="data source=YASIR\SQLDEVENV;initial catalog=Restaurent;integrated
security=True;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
And make sure that
your Dbcontext constructor is like
public RestaurentEntities ()
: base("name=RestaurentEntities")
{
}

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!

Autogenerated default connection string vs. manually added one

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.

EntityFramework ignore login name in connectionString

Hi iam trying to configure my first application with EF but find no way to connect to DB
this is my context
public partial class FunzionamentoContext : DbContext
{
public FunzionamentoContext()
: base("FunzionamentoContext")
{}
static FunzionamentoContext()
{
Database.SetInitializer<FunzionamentoContext>(null);
}
public DbSet<Controllo> Controllo { get; set; }
}
this is connection string (present in app.config file of DAL project since i still don't have UI project):
<?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="FunzionamentoContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=xyzxyz; Initial Catalog=dbName;
Integrated Security=false;User ID=test;Password=test" />
</connectionStrings>
<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>
this is a simply method i make to test connection (only for search if connection is done, next i will rewrite it in a more beautyful way :D)
[Test]
public void TestTrue()
{
FunzionamentoContext fctx = new FunzionamentoContext();
Controllo c = new Controllo();
.id = 1
fctx.Controllo.Add((Controllo)c);
fctx.SaveChanges();
}
When i try to connect i see this error:
FunzIA.UnitTest.DAL.TestFixture1.TestTrue:
System.Data.Entity.Core.EntityException : The underlying provider failed on Open.
----> System.Data.SqlClient.SqlException : Cannot open database "FunzionamentoContext" requested by the login. The login failed.
Login failed for user 'DOMAIN\U123456'.
where DOMAIN\U123456 is my windows account
Why EF use my windows account and not the one wrote in connection string?
I am assuming that you have your DAL in a separate project from the project you're actually running.
Your application will use the config file from the project you're trying to run, and not the one directly related to the DAL project.
By this, I mean, if you're only using the test project (assuming it's in a different project from the DAL) then you need the connection string in the app.config of your test project.

Categories

Resources