I'm trying to use Entity Framework 5 Code First.
I've created model classes and context.
After that following Microsoft instructions I've enabled code migrations.
Than I skipped running my application (during which DB should be created first time) and use Add-Migration command. Migration was generated successfully.
Update-Database call was also successfull. But I'm not seeing my DB at all. It is absent!
SQL Management Studio and Visual Studio Server Explorer show only 4 default system databases and that's all!
I also tried to launch my application - it doesn't change anything.
I'm using
public MyContext() : base("name=MyContext") { }
such type of constructor (so I need specify connection string with MyContext name.
Here is my app.config example:
<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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="BettyContext" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=MyDB.sdf"/>
</connectionStrings>
</configuration>
I have no idea what's going on. Seems that no one has such problem. May be I've missed some evident thing, but howbeit I'm waiting for some help.
Do you see an exception? If you don't see an exception you probably are not looking at the right database. You can try adding some data to the database with your app and then read it. If the data can be successfully added and read and you still don't see the database it would confirm that you are looking at wrong database.
Related
In an ASP.net 4.5 Web Api, locally and in production environments is working fine.
I added the Nuget package Entity framework 6.1.3 to the solution. Without adding model. Locally with EF it is working, but when I publish to production, it throws "error 500".
EF add lines to the web.config:
<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>
In production, when I remove these lines, it works fine (of course without EF).
I tried adding a model then cause the API throws 500.
Is there any way to use EF in this hosting?
Is a problem in the web.config or in the hosting? The api is in a second level directory of a MVC web app.
pd: The hosting uses Managed Pipeline Mode: Integrated.
More info:
When i GET from browser http://max-prueba.somee.com/api/Position/41
it response a status 500 and Server Error
500 - Internal server error. There is a problem with the resource you
are looking for, and it cannot be displayed.
Next step i add line to web config to view description of the error
<customErrors mode="Off"/>
But the response is the same.
I've run into some issues with MSTest when they're run inside teamcity. When I run them inside VisualStudio on local machine, everything works good.
[08:05:21][ProjName.Data.Tests.HistoryTableHandlingTest.HistoryProgressTest] Class Initialization method ProjName.Data.Tests.HistoryTableHandlingTest.Init threw exception. System.InvalidOperationException: System.InvalidOperationException: The 'Instance' member of the Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' did not return an object that inherits from 'System.Data.Entity.Core.Common.DbProviderServices'. Entity Framework providers must inherit from this class and the 'Instance' member must return the singleton instance of the provider. This may be because the provider does not support Entity Framework 6 or later; see http://go.microsoft.com/fwlink/?LinkId=260882 for more information..
Here's my app.config for MSTest project:
<?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" requirePermission="false" />
</configSections>
<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>
Another thing that I'd like to mention is, that I don't use EntityFramework library from NuGet, but it's clone EntityFramework.HierarchyId (it can be found in NuGet as well).
After I rewrote all tests to NUnit, I got the same results.
But it seems, that the main reason of this behavior was, that on the build agent MS Sql Server Express wasn't installed properly.
When I re-installed latest version of SQL Express, everything started to work as a sharm. It seems that system was missing some drivers or libraries for LocalDB.
I hope that this will help someone else.
I got the following error when I used sqlce 4.0 with entityframework 6.0
No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlServerCe.4.0'
My app.config looks like this
....
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />
<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 -->
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" >
<parameters>
<parameter value =" System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<!--providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers-->
</entityFramework>
<connectionStrings>
<add name="FbMultipleInsOrderContainer" connectionString="metadata=res://*/FbMultipleInsOrder.csdl|res://*/FbMultipleInsOrder.ssdl|res://*/FbMultipleInsOrder.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="data source=|DataDirectory|\FBMultipleOrderSync.sdf"" providerName="System.Data.EntityClient" />
</connectionStrings>
...
I tried re-installing EF 6. But no avail.
Any clue on this would be much appreciable.
After installing the EntityFramework.SqlServerCompact nuget package, check that your app.config contains the following (as per #ErikEJ's comment above):
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
(You can leave the line for SqlClient even though you don't really need it.)
ErikEJ has pointed this out, but I'd like to highlight the fact, you MUST remember to install the Nuget package
EntityFramework.SqlServerCompact
I tried following the recommended answer, but didn't realise I didn't have the required NuGet package the App.config was referencing.
I met the issue in my unit tests. The tricky thing was that the error had appeared not constantly.
I managed to solve it by adding the follwing class my my unit tests solution:
public static class Trick
{
public static void FixEfProviderServicesProblem()
{
// this commented line should be used for SQL Server provider
//var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
// this is used for SQL Server CE provider
var instance = System.Data.Entity.SqlServerCompact.SqlCeProviderServices.Instance;
}
}
To achieve this you just need to register the EntityFramework.SqlServerCompact in Package Manager Console,
To do this open power manager console and type below command:
PM> Install-Package EntityFramework.SqlServerCompact
To resolve this problem
Visual Studio Menu -> Tools -> NuGet Package Manager - > Manage NuGet Packages for Solution
Select 'Browse' Tab and search for following 'EntityFramework.SqlServerCompact'
Install it.
It should work.
My issue was the unit tests. You likely only installed the Entity framework for your project, but not your unit tests. To do so:
Right click "Solution" in Solution Explorer (not your project's name)
Click "Manage NuGet Packages"
Search for EntityFramework and press it
You will probably not see a tick next to [Project Name].Tests
This error arose on a User PC. The user ignored a previous error "The ‘DbProviderFactories’ section can only appear once per config file".
Apparently DB2 corrupted the machine config file on her PC, by adding a duplicate (and empty) <DbProviderFactories /> tag.
The solution was to delete the empty duplicate tag. The machine config file is located in [WindowsDir]\Microsoft.Net\Framework[.NET Version]\Config\Machine.config
the solution provided is correct but it does not explain why EF need this assembly. Here is Why...
By default EF's configuration allow you to have a "defaultConnectionFactory" uder entityFramework section. This default factory is configured to "LocalDbConnectionFactory" and its param is "mssqllocaldb".
This factory internally requires "SqlServerCe.4.0" i.e. "SqlServerCompact".
The error happens only if the EF uses its default connection string in DbContext. If EF is provided with some other specified Connection string in your config then this error does not appear. Because EF by default uses the default connection factory.
once you install "SqlServerCe 4.0" the configuration of EF is changed and "LocalDbConnectionFactory" and its param is "mssqllocaldb" are replaced with "SqlServer Ce 4.0". and EF runtime is also able to find the SqlServerCe4.0 Assembly (as it is now part of your references and physically placed in your BIN).
Following is the EF Config before and after installing Sql Server Compact
OLD Config:
<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>
The new configuration is as below:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
and also it added the following section to describe new Factory
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
Don't forget that Package Manager Console takes app.config/web.config from selected as Startup project!
For me, because the programmer is not only one, some programmer is already install EntityFramework.SqlServerCompact, but when I pull in my PC and RUN shows above error message, then I just Uninstall and install again.
Within Visual Studio, all the .dll files that exist in _bin_deployableAssemblies folder need to be set to Build Action : none
All the .dll's for me were set to content.
This is what I set it to, and it worked straight after:
I add the provider code below to the Web.config,and install the EntityFramework.SqlServerCompact package both, and then solve the problem.
If lacking one, it fails.
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact"/>
I'm playing around with EF different workflows. Yesterday I made a new project and Entity Framework 6 was the first suggestion from Nuget so I decided to give it a try, also it is a very small project entirely for learning purposes so I guess it will be good experience to try EF 6 since I've been working mostly with Ef 5.
My Application is based on Code First approach. The structure of the solution is shown in the print screen:
The project CodeFirstClasses is meant to hold my Entites. For simplicity purposes and because I follow a tutorial I use only one class as you may see - Customer.cs. There I have :
public class RewardContext : DbContext
{
//Specify the name of the base as Rewards
public RewardContext() : base("Rewards")
{
}
//Create a database set for each data item
public DbSet<Purchase> Purchases { get; set; }
public DbSet<Customer> Customers { get; set; }
}
And the other classes - Purchase and Customer which are trivial, so I won't paste them here.
The other project as you can see is Windows Forms project with just one form and button on it. On the click event of the button I have all the logic for adding new records to my two entities hardcoded. Here is just a part of it:
//some code...
//Add the record and save it
context.Customers.Add(newCustomer);
context.Purchases.Add(newPurchase);
context.SaveChanges();
MessageBox.Show("Record Added!");
So far nothing different from what I'm used to with EF 5. I can build the project, I can run it, and everything is executed as expected. However I get this warning from the title :
Warning 1 The element 'entityFramework' has invalid child element 'providers'. List of possible elements expected: 'contexts'. And even though I'm using mostly MS SQL Server Management Studio I've noticed that I'm not able to manage my connections/databases from the IDE - Visual Studio 2012, but this was not an issue with EF 5.
My research narrowed down the possible source of problem/solution to manually changing the App.config file, but this is an area where I haven't got much experience especially when the IDE took care of it until EF 6. So I'll post both my App.config files for this solution :
The one from the CodeFirstClasses 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>
<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>
And from my TestCodeFirst 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>
<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>
</configuration>
And the other possible solution that I found is : updating the xsd for "validating" EF config section in web/app.config file to recognize newly added EF6 elements which I'm also not aware of how exactly to do it.
Even though when I open the MS SQL Server Management Studio I see the database created for this application, the records are saved and generally it seems to work but yet I would like to resolve this warning and get to know how to set up my applications based on EF 6 right.
You can install the EF6 Designer for VS2012 from here and it will update the schema that validates config files.
The configuration schema was changed from version 5 to 6. As it says, the providers node was replaced with a contexts node.
The idea is that you can configure the providers individually instead of all contexts using the same provider. (This goes in tandem with being able to have multiple contexts that reside within one database. This used to be called multi-tenant but was later renamed to be more concise)
i have a solution that contains an MVC project and windows class library project that uses entity framework and is a data access layer. I tried to enable migrations with the following package manager console line
Enable-Migrations -ProjectName PortlandRoad.DAL -ContextTypeName PortlandRoadDBContext -Force
I try to update the database using the following line
Update-Database -Verbose -Force
if i do this with the mvc project as the startup project it works, but uses the connection string in the mvc project web.config. If i do this with the dAL project as the startup project i get the following error :
A file activation error occurred. The physical file name '\PortlandRoadDB.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
the app.config file for my DAL project is as follows :
<?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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!--<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="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=PortlandRoadDB;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\PortlandRoadDB.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
can anybody tell me how to correct this so that the migrations work specifically for the dal project and are not dependent on the MCV project being the startup project
thanks
I've the same issue in a WPF project.
I think that you have two options.
Option 1
At startup in you windows project try to specify the correct path to your database using
AppDomain.CurrentDomain.SetData("DataDirectory","your\physical\path");
With this, you will have the same error but your migrations can still being applied to your principal database.
option 2
Find a way to replace dynamically this |DataDirectory| in your app.config file before starting your application. (.bat , or .ps or ...).
another option: The bad one.
Before running your migration change the path to you DataDirectory to a physical temporary one in your app.config (this file will help you keep up to date migrations history)
before launching your application replace the temporary file path by |DataDirectory| and change this parameter in your startup with the App.config
With this work around, if your are planning to deploy your application, you will keep track of all migrations in order to anticipate futures database modifications.
Voilà.
Could it be that you're using "|DataDirectory|" in the connection string in the DAL project? Since "|DataDirectory|" is an Asp.Net folder and the DAL project is not an Asp project it probably doesn't recognize that as a directory and it probably doesn't exist thing the DAL project.