How to consume an Entity Framewok (v6) Library? - c#

I can make an entity framework console application that displays the customers in the Northwind database.
However, when I try to create the Northwind Entity Framework in a separate class library that is consumed by a simple C# console application in a separate sub-project, I encounter some problems.
I read http://www.dotnetcurry.com/showarticle.aspx?ID=617
and watched http://msdn.microsoft.com/en-us/data/ff628208.aspx and followed the directions by copying the connection string in the app.config from the library to the console mode program directory and adding a reference to my northwind EF class library.
I'm still getting this exception when trying to create the dbcontext variable in my console program:
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
Additional information: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
After some more google searching I tried adding this code:
public abstract class BaseDomainContext : System.Data.Entity.DbContext{
static BaseDomainContext() {
var ensureDLLIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
}
}
The problem now is I get the red squiggly line underneath "SqlServer" -- apparently there is no such namespace in my copy of System.Data.Entry. I just upgraded to EF 6 with nuget.
Can anyone help me resolve this?
Thanks
Siegfried
Sun Mar 30 2014:
Forgot to mention: I'm using Visual Studio 2013 on Windows 8.1. Here is my app.config from my console mode demo program, most of which was copied from the class library app.config. Now that I think about it, who is looking for that connection string? Is it the class library or my console mode demo program? What should be the name of the connection string?
<?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" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="NorthwindEntitiesLib" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=KM;initial catalog=Northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Mon Mar 31 2014:
Everything works fine for VS 2012. I just add the reference to the class library, cut and paste most of the App.config file from the library app.config to the console mode app.config and everything works. What can we conclude from this? Looks like there is a bug in VS2013 with EF 6. Can anyone help me workaround this bug?
Ben: I tried your suggestions and, judging by your XML you posted, it looks like you are using EF 5. I just upgraded to 6. I'm still getting the same errors in VS 2013.

It is in System.Data.dll i.e. System.Data.SqlClient.
Make sure you have a reference to this.
Can you post your connection string?

This one works for me - I just created a new project and added a new .edmx file to the project and called:
using (YourDbContext db = new YourDbContext(){///}
This calls the parameterless constructor for the context which uses the default connection string setting from you app.config. Take a look at the constructor yourself to see what is auto-generated and you'll see what connection string is being used.
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="NorthwindEntitiesLib" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=KM;initial catalog=Northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>

Related

Entity Framework 6: The context is being used in Code First mode with code that was generated from an EDMX file

I'm creating WPF application using Entity Framework 6 with database first approach. EF did everything for me and i'm able to connect to the database and so far downloading data works, so connection exists. But every time i add user control it gives me new error that connection string was not detected. Program works fine anyway, but its hard to program when your error window is flooded with it.
I have found out that changing context from:
public MediaRentalEntities()
: base("name=MediaRentalEntities")
{
}
To this:
public MediaRentalEntities()
: base("MediaRentalEntities")
{
}
Should fix the issue, but it doesn't.
Now it throws exception (and shows this error multiple times, based how many user controls i have, currently 3):
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
This is my current 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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<entityFramework>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="MediaRentalEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;data source=localhost;initial catalog=MediaRental;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
It's starting to be tiring, i'm tempted to change to EntityFrameworkCore or even Dapper, it feels like EntityFramework6 is against the user, but WPF has way more functionality on .NET Framework.
in connection string replace MyModel with "MediaRentalEntities" .It will work
Or
If you have generated it using DB first then you will already have context class where code is like
public MyModel()
: base("name=MyModel")
{
}

Entity Framework 6 (code first) Add-Migration puts wrong provider to the edmx schema

I have a project which is originally used System.Data.SqlServerCe.4.0 (MSSQL Compact Edition 4.0) data provider. Then I've made a branch, changed config file and references for System.Data.SqlClient (MSSQL provider), uninstalled EntityFramework for MSSQLCE nuget package. Everything in the branch project works fine except two things: Add-Migration and Database seed script fail with the next error:
Schema specified is not valid. Errors: (0,0) : error 0175: The ADO.NET provider with invariant name 'System.Data.SqlServerCe.4.0' is either not registered in the machine or application config file, or could not be loaded
I've tried to find the source of the issue and finally found that EDMX schema, which is stored in the __MigrationHistory of the MSSQL project database, contains the next line:
<Schema Namespace="CodeFirstDatabaseSchema" Provider="System.Data.SqlServerCe.4.0" ProviderManifestToken="4.0" Alias="Self" xmlns:customannotation="http://schemas.microsoft.com/ado/2013/11/edm/customannotation" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
But I don't understand, why it is generated with the Provider="System.Data.SqlServerCe.4.0" option ? I've checked that my branch project doesn't have any file, which contains SqlServerCe substring (did file search in OS). I've tried to reinstall EntityFramework NuGet package, doesn't help as well.
App.Config:
<?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>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<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="AppDBContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=AnalyticDB;Persist Security Info=True;Trusted_Connection=Yes;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
EF version: 6.1.2
Thanks!

Common Entity Framework Project "No Entity Framework provider found for the ADO.NET provider"

So I looked at entries with the same error, and either it is not the same problem, or I am not understanding it.
I have a solution with several projects. They use a common Entity Frame Work 6 and include it in there references. The WCF project works great using the Entity Frame to get data from the database. But my console application gives me,
No Entity Framework provider found for the ADO.NET provider with
invariant name 'System.Data.SqlClient'
when executing the same code calling the Entity Framework.
I think I am missing something in the .config file, but my connection strings are all the same.
Entity Framework App.Config:
<configuration>
<connectionStrings>
<add name="SafetyPortalEntities" connectionString="metadata=res://*/EntityModels.SafetyPortalModel.csdl|res://*/EntityModels.SafetyPortalModel.ssdl|res://*/EntityModels.SafetyPortalModel.msl;provider=System.Data.SqlClient;provider connection string="data source=ndmasdev;initial catalog=SafetyPortal;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</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>
WCF Web.config:
<configuration>
<connectionStrings>
<add name="SafetyPortalEntities" connectionString="metadata=res://*/EntityModels.SafetyPortalModel.csdl|res://*/EntityModels.SafetyPortalModel.ssdl|res://*/EntityModels.SafetyPortalModel.msl;provider=System.Data.SqlClient;provider connection string="data source=ndmasdev;initial catalog=SafetyPortal;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Console App.config:
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<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="SafetyPortalEntities" connectionString="metadata=res://*/EntityModels.SafetyPortalModel.csdl|res://*/EntityModels.SafetyPortalModel.ssdl|res://*/EntityModels.SafetyPortalModel.msl;provider=System.Data.SqlClient;provider connection string="data source=ndmasdev;initial catalog=SafetyPortal;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
You can use the package manager console (Tools->Nuget Package Manager->Package manager console) and add entity framework to the Console app using
install-package entityframework
Be sure to choose the console app in the Default project dropdown in package manager console.
After much frustration I finally figured out what was wrong.
A WCF project automatically includes a reference for Entity Framework in the References so it worked fine.
The Console application did not have a EF reference, but when trying to add a new reference, it doesn't show up in the options list anywhere and including the other project didn't include the EF reference. (I have no idea why) So I selected "EntityFramework" from the References in the EF project, copied the path for it, and then did a browse add in the Console Project References with the path from the EF project.
There has got to be a better solution for this, if you post it, I will select yours as the answer.

Code First can't enable migrations

I'm trying to enable migrations but it's throwing an exception:
Checking if the context targets an existing database...
System.TypeInitializationException: The type initializer for 'System.Data.Entity.Migrations.DbMigrationsConfiguration`1' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: The 'name' attribute must be specified on the 'section' tag.
I'm assuming that the App.config file is not correctly set up (it was automatically set up when I added EF package). All I did was add the connection string:
<?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" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<connectionStrings>
<add Name="MyContext" connectionString="data source=MYSERVER;initial catalog=CodeFirstTest;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
I'm using SQL Server 2008 R2.
As I do have a connection string, I don't believe I need the defaultconnectionfactory. Am I correct? (Note: Even without this section I'm still getting the same exception)
What else am I missing?
I had the same issue when my <connectionString /> entry is on top part of the Web.config, Right after <configuration>. Then I tried moving it right before </configuration>, and it worked.
This is mainly to do with the config file. So the actual stack trace that helps is "System.Configuration.ConfigurationErrorsException".
There can be many reasons but they all majorly include the correction in the config file as answered earlier.
Couple of possibilities which are little different than this are given below (But the stack really tells us)
One possible out of the way reason can be that, your project where the migrations are getting enabled can be different from the startup project. So be sure to add -StartUpProject to your nuget commmand.
Version of the entity framework used can be different in case of two different projects.
I met with the same issue. My problem is that there are double connection string on the Web.config file. like as below:
<add name="DB1234" ..../>
<add name="DB1234" ..../>
So we have to check our web.config file first!
Good Luck!
check the spelling of your 'connectionString' and make sure it is 'connectionStrings' I omitted the 's' before in my own case.
After adding the 's', that solved it.
In my case I had several projects in the solution and another project was set as the StartUp project. Setting the project that I was trying to enable migrations for as the StartUp project resolved it.
In my case, using DevExpress MVC generated template, it need to add extra lines after <sectionGroup name="devExpress">...<sectionGroup/> in web.config
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
in my experiences, for example is that all the information that is used to establish a connection with the database is the one that comes from the config file that is in the startup-project, and not the one that is in the project where i am generating or using the enable-migrations or update-database instructions, example i have project PRINCIPAL and another project DATA,i use the DATA project as my default-project only when running the packages in Packager console Manager, but the config file that really use is the one in PRINCIPAL.
Include this into <configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
In my case this line is omitted when I have 2 instances of Visual Studio open.
Close all instances of the Visual Studio, open and reinstall EF via interface Nuget or Console to avoid this error
Check the webconfig, For example: I had the app settings like this:
<configuration>
<appSettings>
<add key="dhx_license" value="value"/>
</appSetting>
.....
and threw that error. But then I realized appSetting was duplicated below so I moved the and the error vanished. Thanks.
Like #Lester answer check web config. It must look like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
...
</configSections>
<appSettings>
...
</appSettings>
...
<configuration>
I had the same issue. But I found there are two <connectionString /> in my Web.config,
I had to remove one connection string and it work fine for me.

EF6.0 Code First - Change connection

After developing EF codefirst application locally,
I copied the database from localdb with generate scripts and create a new one at azure.
I added connection string to config file 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="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Server=tcp:XXXXXXX.database.windows.net,1433;Database=XXXXXX;User ID=XXXXXXXXXXX;Password=XXXX;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"/>
</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>
When I try to call an object, I get this exception:
"Invalid object name 'dbo.Banner'."
DB connection is correct. I can connect with SQL Server Management Studio.
What is wrong with this code?
Does the manually creating DB cause the problem?
This problem happen specially when you are restoring database to another server and if you have changed the databse username.
To solve this problem the best way is to change all SCHEMA to dbo.
To change SCHEMA execute following code through your MSSQL Enterpeise manager
ALTER SCHEMA dbo TRANSFER oldSchema.TableName
It seems that the tables has not been created.
Some pointers:
Did you enable Automatic Migration?
AutomaticMigrationsEnabled = true;
You maybe prefer doing a manual update/creation?
In that case, select a project containing the configuration that points to your Azure DB and in the Package Manager console:
update-database
Or you can do it in code as well using the MigrateDatabaseToLatestVersion initializer class.
Here are some additional information for reference:
- MSDN: Code First Migrations
- ASP.NET: Code First Migrations and Deployment with the Entity Framework in an ASP.NET MVC Application

Categories