I have a test project which references another project, which in turn references a third project containing my Entity Framework 5.0 file (edmx). I find that I can run database-driven unit tests directly from Visual Studio, but when I run from mstest I get the following errors:
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException:
Code generated using the T4 templates for Database First and Model
First development may not work correctly if used in Code First mode.
To continue using Database First or Model First ensure that the Entity
Framework connection string is specified in the config file of
executing application.
I have non-database connecting unit tests which run fine. I've fiddled with my various app.config EF connection strings and they seem to be OK (every tests runs fine on Visual Studio). The problem is when I run mstest from a command line on my desktop or on a build server. This is the command I use:
MSTest.exe /nologo /searchpathroot:"\Binaries"
/resultsfileroot:"\TestResults"
/testcontainer:"\Binaries\driver.orderedtest"
/testcontainer:"\Binaries\EF.DataAccess.dll"
/publish:"http://"
/publishbuild:"vstfs:///Build/Build/99" /teamproject:"ProjectName"
/platform:"Any CPU" /flavor:"Debug" /noisolation /detail:errormessage
/detail:errorstacktrace /detail:stderr
I have references to all dll's in the test project, as outlined here: Entity Framework custom tool does not correctly embed or load the model as resource files
I've been on this for a few days off and on, and it looks to me that this is an EF 5.0 bug, but according to the connect link this should be fixed, but it doesn't seem to be the case.
Related
I am running a migration script using package manager console after setting dependencies in corresponding files in dot net core based project and i am receiving below error after running the below migration command in package manager console ,
Add-Migration "InitialCreate"
Error received :
Unable to create an object of type 'PaymentDetailContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
I have gone through different ways to troubleshoot this issue inorder to create a migration file
I am logging using windows authentication method and kindly help me to resolve this issue in visual studio 2022
Entity framework Dot Net Core Error In Adding Migrations
I have tried to check all the corresponding files whether any spelling mistakes in connection string file , added corresponding packages using browse option and installed
I am expecting this error to be resolved (below one ) after executing the script
Add-Migration "InitialCreate"
Unable to create an object of type 'PaymentDetailContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
and thereby generating the migration script inside web api project
Locally my database works fine. I try to put a server database to the same version as my development version.
In Visual Studio, I ran this command:
dotnet ef migration scripts lasknown_script_that_was_executed_on_prod_server
where I use the value of
lasknown_script_that_was_executed_on_prod_server
as found on the production server by querying:
SELECT TOP 1000
[MigrationId], [ProductVersion]
FROM
[MyProject].[dbo].[__EFMigrationsHistory]
and yes it's in my source code as well, so seems OK, my code knows that version.
After I perform that command, it creates a large output but on top of that it shows an error
Build started...
Build succeeded.
Error writing app settings | Cannot perform runtime binding on a null reference
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.5 initialized 'ApplicationDbContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.5' with options: > None
BEGIN TRANSACTION;
GO
CREATE TABLE [MyApplication] ( ...my firs db create..?? ...
I assume therefore the output code is missing something that should go before the very first initial database creation.
(as my prod server is not at that version, it shouldn't start with the first migration).
Locally it works fine, however, and it was set up with code-first.
So it was generated by code, it should migrate as well by code.
I am setting up an Azure Release Pipeline and I need to execute any pending DB Migrations as part of the release.
I have been scouring the internet for over an hour and everything I can find is about dotnet Core, while the database is EF6 on .Net Framework, not dotnet Core (I've done this several times before for Core).
The problem, as I see it, is that EF6 works using Visual Studio's built in Package Manager Console - This just doesn't exist in an Azure Pipeline; It's a Visual Studio weirdness.
There seems to be several ways I can skin this cat, in my head, but I can't figure out how to start with either of them within the context of the pipeline...
OPTION 1: Run the Migrations on the Pipeline - but... how?
OPTION 2: SQL Scripts - Requires running the Package Manager to generate them so they can be run (if I could do that on the pipeline then I'd just run it anyway so these would have to be created locally and committed with the code which is somewhat backward as a solution IMO)
OPTION 3: Write a console app - Do I really have to do this??
You can try Entity Framework Migration Extensions.
This task allows a Build / Release to provide database connection parameters and execute an Entity Framework 6 migration against the database.
Build your project to an output folder and include the migrate.exe executable that comes with Entity Framework 6.
Create an automated build that packages up your files and makes them accessible during a Release.
Create a Release definition for the relevant Build
Add an EF6 Migration task. Once that task is added to an environment within the release, you'll need to enter the appropriate parameters to configure it. All file path parameters should be within the file system for the build, none of them are for TFS source control paths.
You can also check this article.
The answer here is to use the ef6.exe command line tool and make sure it gets shipped with your build.
This could be useful to anyone here until Microsoft update the non-existent docs: http://github.com/dotnet/EntityFramework.Docs/issues/1740 - This contains a table with a kind of translation matrix between the two.
I've got a full .NET Framework 4.6.2 Web API app that I've installed Entity Framework Core 1.1.2 into. It contains some classes, a DbContext class and has the relevant EF Core NuGet packages installed.
When I run Add-Migration Initial in the package manager console within Visual Studio, it correctly identifies the DbContext in the project and produces the migration class as well as a snapshot. The migration looks correct, given that within the Up method, it shows a number of create tables for each of the classes I want, it shows the expected columns for each and the constraints I'd expect, so that looks good. Also, within the Down method, it drops all the tables (which makes sense since this is the first migration done). This migration class is created in the /Migrations directory within the project.
When I run Script-Migration in the console next, it produces a SQL script that is incorrect, in that it only creates the table for the EFMigrationsHistory, as follows:
IF OBJECT_ID(N'__EFMigrationsHistory') IS NULL
BEGIN
CREATE TABLE [__EFMigrationsHistory] (
[MigrationId] nvarchar(150) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
);
END;
GO
This SQL file is created in the bin/Debug directory for the project.
I would expect that the output of this Script-Migrations command contain the SQL version of the Up method in the migration class that was produced by the previous Add-Migrations Initial command, but alas, this is not the case. If I run Update-Database, it runs against this SQL file and continues to ignore the existing Migrations.
Similarly, this appears to be a larger issue with EF Core, because if I attempt to do a Remove-Migration as suggested in the console after running Add-Migration, it is also unable to find the Migration it just produced and gives me the following error:
No ModelSnapshot was found.
And I know this can't be the case because I see it right there in the Migrations folder along with the initial migration class it created.
What's going on and is there any known workaround to get these tools working appropriately?
Update
While testing, I've found that if I create a new solution with just these few parts in it, it works fine. However, in my original solution, I have these projects within a number of solution folders, so perhaps that's the issue at hand, because putting the new project in a solution folder causes the same issues observed in the rest of this question.
My pre-generated views for EF4 Code First using this T4 template does not work in the build server. I am not re-generating the view in the build server, just compile and run the MSTest. Error is thrown when the tests are ran:
System.Data.MappingException: The mapping and metadata information for
EntityContainer 'DB' no longer matches the information used to create
the pre-generated views
I ran the same template in another machine and the hash values are different. I guess this is the reason why its it does not work in the build server. The hash values are different at runtime in other machines, hence the verification fails and throws the exception.
Im using:
VS 2010 Pro
.Net Framework v4.0.30319
Entity Framework v4.2 (Code First)
EF CodeFirst View Generation T4 Template for C# (v1.0.1) - slightly modified GetEdmxSchemaVersion to return the correct EntityFrameworkVersions version for my setup.
using Class Library project template
The tests that I am running connects to a SQL DB file that is checked in with the code.
I have checked the build server and its using the same EF dll version and .Net Framework version.
Any idea why the hash values are different?
UPDATE:
I've generated and compared two XML file from two dev machines using EdmxWriter.WriteEdmx().
Here is schema version (the same in both machine):
<?xml version="1.0" encoding="utf-8"?>
<Edmx Version="2.0" xmlns="http://schemas.microsoft.com/ado/2008/10/edmx">
The obvious difference are the order some nodes in the XML files. Here is an example:
Machine 1:
<EntityType Name="PersonEntity" BaseType="Self.Entity" />
<EntityType Name="CompanyEntity" BaseType="Self.Entity" />
Machine 2:
<EntityType Name="CompanyEntity" BaseType="Self.Entity" />
<EntityType Name="PersonEntity" BaseType="Self.Entity" />
Any idea why they are in different order?
UPDATE 2:
The Edmx (xml) from the build server is also different for the other 2 dev machines. Again, the order of some nodes are different.
Machine 1 and build server both have System.Data.Entity.dll (same File and Product version -- v4.0.30319.1) in %windir%\Microsoft.NET\assembly\GAC_MSIL\System.Data.Entity\v4.0_4.0.0.0__b77a5c561934e089.
UPDATE 3:
I also looked at the version of System.Data.Entity.Design.dll. The T4 template references this assembly. Machine 1 has two copies of this dll ... in GAC (v4.0.30319.233) and in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0 (v4.0.30319.1). This is also true in the build server and Machine 2. I wonder if hash validation function during runtime is using this dll as its not referenced in my project. If it does, which version is used. But then again, the hash validation is successful in Machine 1.
I'm answering my own question. Here's how we solve the main problem (how to pre-generate views in EF Code First that is usable in different machines). I am now using .Net runtime 4.0.30319.17929.
In the ABC.csproject where MyContext.cs is located, delete the T4 template and MyContext.Views.cs.
Compile ABC.csproject
Create a console app that will generate the views. I copied most of Pawel's T4 template. Reference the ABC.dll (and other required dlls). Here's one of the changes:
var edmx = GetEdmx(typeof(MyContext));
Save the string output of GenerateViews() to a text file.
Run the console app.
Add new file named MyContext.Views.cs to ABC.csproject and copy the content of the text file to this class.
Recompile ABC.csproject
I find my solution insane and must be simplified or automated but it works.