Entity Framework DbContext Connection string in app.config/web.config not being seen - entity-framework

So, I have followed this instruction from ADO.NET team blog to try to make a small test project.
I have double-checked everything. It doesn't seem to work and keeps saying connection string is missing.
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx
Step. 1
Build this UserModels.dll. In the dll, App.Config file, edmx generated this connection string: (hit the 'test' button when making it, and it connects successfully, and generated the edmx diagram of all the tables from 'UserDatabase')
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="UserModelsContainer" connectionString="metadata=res://*/UserModels.csdl|res://*/UserModels.ssdl|res://*/UserModels.msl;provider=System.Data.SqlClient;provider connection string="data source=MyDesktop\SQL2008;initial catalog=UserDatabase;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Step 2.
Then I made a test project:
class UnitTetst1 ....
TestMethod1()....
using (var db = new UserModelsContainer()) {
int i = db.Users.Count(); // <---expecting '0' for a new db, but I get an exception
}
---------PROBLEM HERE -----------------
Step 3. Run the test. Then I get an error InvalidOperationException like this:
"No connection string named 'UserModelsContainer' could be found in the application config file."
Seems like DbContext doesn't know where to pick up the connectionStrings from App.Config??
Please help~~

When running a program, it's the app.config of the .exe file being run that is read. The app.config of the .dll is never used. Since UserModel.dll is a dll, there must be an .exe (or web site) somewhere that you run. Place the connection string in that exe's app.config (or if it is a web site in the web.config).

I had this issue when I was attempting to do an update-database command from the "package manger console". I had a separate project for my code first Data access layer and another for my web project, etc
I was using the following command: "update-database -projectname MYPROJECTDANAME -CONNECTIONSTRINGNAME CONNECTIONSTRING -Force"
so it pointed at my MYPROJECTDANAME project however it takes the connectionstring name from startup project you have specified. Therefore make sure the project you have marked as the startup project has the required connection string.

Related

Resolving connection string in EFv6.3 in ASP.NET Core Windows service project

I have an ASP.NET Core application running as a Windows Service. Due to project requirements, I am using Entity Framework v6.3 (as opposed to using EF Core).
I am having trouble retrieving the correct connection string when performing a migration and also upon publishing the service to a server. When running the service locally, the connection string is retrieved successfully.
As I understand it, Entity Framework 6 is supposed to retrieve connection strings from web.config or app.config files, right? Therefore, I have an app.config file containing two connection strings, e.g.
<connectionStrings>
<add name="DataContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
<add name="CrmContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
</connectionStrings>
In my Startup class, I have registered both database contexts, e.g.
services.AddTransient<DataContext>();
services.AddTransient<CrmContext>();
On a Razor page, when I instantiate both data contexts on my local machine I can see the correct connection string is being resolved for both contexts (by using _crmContext.Database.Connection.ConnectionString).
When I attempt to add a migration using the update-database command on my CrmContext (automatic migrations enabled), the correct connection string isn't resolved. Instead, it defaults to creating a LocalDB database using the default connection string: (localdb)\MSSQLLocalDB
How come it isn't using the connection string I have provided in my app.config file? I also a web.config file but it doesn't resolve from there either.
CrmContext.cs
public class CrmContext : DbContext
{
public CrmContext() : base("CrmContext")
{
Database.SetInitializer<CrmContext>(null);
}
public IDbSet<CustomerDetails> CustomerDetails { get; set; }
}
CrmConfiguration.cs
internal sealed class CrmConfiguration : DbMigrationsConfiguration<CrmContext>
{
public CrmConfiguration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(CrmContext context)
{
...
context.SaveChanges();
}
}
I've tried to explicitly update the CRM connection by specifying my CrmConfiguration file:
update-database -ConfigurationTypeName CrmContext
When I do this, it creates and updates the LocalDB database instead of using my connection string.
I've also tried to explicitly referencing the connection string:
update-database -ConnectionStringName "CrmContext"
This results in this error:
No connection string named 'CrmContext' could be found in the
application config file.
My CrmContext class exists within my ASP.NET Core windows application where my DataContext class exists in a separate 'Data' project (as it's shared with an ASP.NET MVC v5 application)
When I publish my service and install the application as a Windows Service, I found that it also doesn't pick up the connection strings at all from any of the config files - it again just looks for the default localdb database. As I understand, it should pick it up from my PaymentBatchProcessorService.exe.config file, right?
My PaymentBatchProcessorService.exe.config file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<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="DataContext" providerName="System.Data.SqlClient" connectionString="redacted" />
<add name="CrmContext" providerName="System.Data.SqlClient" connectionString="redacted" />
</connectionStrings>
</configuration>
As per Microsoft documentation, it should be possible to load in the additional XML configuration files via the following code in the Program.cs file, but EntityFramework still didn't pick up the connection strings:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostingContext, config) =>
{
var workingDirectoryPath = Environment.GetEnvironmentVariable(EnvironmentVariables.ServiceWorkingDirectory);
config.AddXmlFile(Path.Combine(workingDirectoryPath, "app.config"));
config.AddXmlFile(Path.Combine(workingDirectoryPath, "web.config"));
})
e.g. in the above sample, the working directory path resolves to the location where my .exe is for the Windows Service.
Thanks for reading this far!
When you deploy your service, the .config file should instead be called servicename.exe.config. It should reside on the same folder where the service was registered with installutil. See Windows service app.config location.

Single Connection String with Multiple Entity Framework Models(Data First)

I have 3 different project having their respective EF entity data model pointing to same database.I don't want to save connection string in each of these project's app.config file but want to share it between my models.
I see this link on stackoverflow How to share a connection string between multiple entity data model.
But the problem with it is if I will update the EF model it will overwrite the code in EF Model's context and it will inherit from DbContext not from BaseContext.
Please help how can I resolve this.
You have to move your connection string in a separate config file:
ConnectionStrings.config
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="connectionString"
connectionString="Integrated Security=SSPI; Persist Security Info=False; Initial Catalog=DbName; Data Source=.\SQLExpress;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Modify the connection string so that fit your requirement.
Then you can share it with all your projects like that:
1) Open your App.config (This file found in your project)
2) Add this line code somewhere behind </configSections>
...
<connectionStrings configSource="ConnectionStrings.config"/>
...
The trick in configSource:
"Gets or sets the name of the include file in which the associated configuration section is defined, if such a file exists."
https://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource(v=vs.110).aspx
What will happened:
ConnectionStrings.config must be first copied
All YourApplicationName.config will reference the shared connection string config file.
If the project does not have any App.config then just add it! or you can also loaded manually with ConfigurationSettings.
This is the best way to share the database configuration between the app.configs and when you change for example the Sql Server name, then you have only to modify the ConnectionStrings.config and not all App.configs!
It resolved as connection string always picked from MVC project and all other class library projects are referencing it automatically.

Code First connection string

I have an error:
An exception of type 'System.Data.Entity.Infrastructure.UnintentionalCodeFirstException' occurred in DataAccess.dll but was not handled in user code
Additional information: 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.
In DataAccess project I have an EF 6 with App.Config file with string:
<connectionStrings> <add name="CVJobOnlineEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model 1.msl;provider=System.Data.SqlClient;provider connection string="data source=STEFAN-PC\SQLEXPRESS;initial catalog=CVJobOnline;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
and in my second project, which is the main Start-Up project I have in WebConfig:
<connectionStrings>
<add name="CVJobOnlineEntities"
providerName="System.Data.SqlClient"
connectionString="Server=.\SQLEXPRESS;Database=CVJobOnline;Integrated Security=True;"/>
So, obviously I am mixing EDMX and CodeFirst conn strings, but, I need it CodeFirst because of my Identity tables which I was incorporate in my SQL SERVER DB.
Also in my DbContext, I recalled base to use FirstCode (Model1.Context.cs):
public partial class CVJobOnlineEntities : DbContext
{
public CVJobOnlineEntities()
: base("name=CVJobOnlineEntities")
{
}
You must specify your connection string only once at the entry point of your application. Your DataAccess project does not need a connection string if it is not executable. Cut & paste the connection string from your DataAccess project to the web configuration file of your application entry point, overwriting the old one.
The problem was not exactly mixing two types of connection strings, since the one from DataAccess was never read by the Entity Framework. The one provided at your entry point config was just wrong in your scenario, because you are using model-first and not code-first.

EF5 Code First Migration problems publishing to IIS

I've created a MVC 4 project which uses EF5 Code First with migrations.
Because I was new to this topic I used the following article.
Now that the development is finished I want to publish to IIS (I use FTP or Web deployment package). So before publishing I changed the connectionstring to the right db server.
But after publishing the site I get an exception when accessing pages which make use of the DB. The exceptions refers to the fact that he can't connect to the database.
Because of these problems I decided to try it out locally on another DB server than the default one "(LocalDB)\v11.0". BTW: "(LocalDB)\v11.0" works like a charm...
While debugging I got a better look at the error.
Here is an image of the error:
What I've already tried:
Generate a sql script by executing "Update-Database -Script
-SourceMigration:$InitialDatabase" in the Package manager console. After I ran this script on the dbserver to create the db. Tables were
created but the error was still there.
I changed my connectionstring to all kinds of combination with no
results
I already used a custom user for the app pool in ISS and gave this user full rights to the DB server and the db.
Here is the most important part of my web.config:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=LOCALHOST\MSSQLSERVER;Initial Catalog=ProjectX;Integrated Security=TRUE;MultipleActiveResultSets=True" />
</connectionStrings>
And
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=LOCALHOST\MSSQLSERVER; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
My DBCcontext class constructor looks like
public DBContext(): base("DefaultConnection")
{
}
I guess I am missing something, this is the first time I use EF Code First with migrations.
This problem is really driving me crazy. I am out of ideas.
Just found out that the problem was caused by the connectionstring.
The string was incorrect, seems like you if you have a default SQL Server you just need to use
"Data Source=LOCALHOST".
I guess because of all the problems I had that day with the deployment i overlooked the easy parts. Yust make sure you the following things are true when you have problems like I did:
Your connectionstring has the same name as your DBContext. Another sollution could be to do like i did and add the connectionstring name to the base:
public DBContext(): base("DefaultConnection")
{
}
If you also have the defaultconnectionfactory set. Make sure to also update the Data Source there. This was one of the problems I struggled with. I didn't check the bottom of my web.config ...
If the problem still persists you can use EF profiler to have a look at the connectionstring when your app of site is accessing the DB.

Compiler error using EF4 as a separate project than my MVC project

I'm trying to follow the general consensus that it's best to put one's domain objects in a separate project than their MVC project, but am getting the following compiler error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
Source File: C:\Users\Kevin\documents\visual studio 2010\Projects\HandiGamer\HandiGamer.Domain\Entities\HGDomainModel.Designer.cs Line: 44
Line 42: /// Initializes a new HGEntities object using the connection string found in the 'HGEntities' section of the application configuration file.
Line 43: /// </summary>
Line 44: public HGEntities() : base("name=HGEntities", "HGEntities")
Line 45: {
Line 46: this.ContextOptions.LazyLoadingEnabled = true;
I'm a bit confused, as HGEntities is there in the entity's App.Config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="HGEntities" connectionString="metadata=res://*/Entities.HGDomainModel.csdl|res://*/Entities.HGDomainModel.ssdl|res://*/Entities.HGDomainModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\HandiGamer.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Do I need to add the connection to my MVC Web.Config or something?
Yes you need to add it to your MVC Web.Config file.
Since you have an ASP.Net MVC project in place, the connection string must be present in the web.config of your MVC project where the runtime will be looking to find it. Basically any connection string should be in the config file of your executable project (i.e. where the .Net threads started from by CLR). So just copy and paste the whole connection string into your web.conig and you're done!