Publish Web dialog doesn't detect my entity framework 5 context as Code First - entity-framework

I've recently upgraded a WFC project that uses Entity Framework from v4.3.1 to 5.0.
I'm running Coded migrations only (no automatic migrations).
Previously, I was using the Publish Profiles to deploy this solution and apply the migrations. Since upgrading the project to EF5, the migrations portion no longer works and the publish dialog doesn't detect the context as having code-first migrations.
Specifically, the .pubxmlfile changed from detecting my context as <Object Type="DbCodeFirst">to <Object type="DbDacFx"> which is incorrect for my context.
As a workaround, I've manually added the <entityFramework> database initializer configuration to my web.config transforms, but I'd like to understand why the publish profiles aren't working. That was a much nicer solution.

It once happened on me when merging another developer's commit and triggered Visual Studio project reload. That's how it caused the "DbCodeFirst" to "DbDacFx" change.
If I restart Visual Studio then everything goes back to what it should be.
Just another thought.

You probably missed adding the reference to EntityFramework into your project. By just adding the reference you should be able to control whether or not the DbCodeFirst option is available or not.

As this post suggests, try using the fully-qualified name of your DbContext as the name of the connection string. Instead of:
Web.config
<connectionStrings>
<add name="MyContext" .../>
</connectionStrings>
Use:
Web.config
<connectionStrings>
<add name="MyNamespace.AnotherNamespace.MyContext" .../>
</connectionStrings>
In my case, in order to use my existing publish profiles (.pubxml), I also had to manually edit the <ObjectGroup Name="..." ...>. Probably recreating the publish profiles would work too.

I had the same issue but not in the same context.
I had been using Code First Migrations with existing ASP.NET MVC 5.2.3 application using EF 6.1.3 for a month without issues. At one point in time I added support for Windows Azure Storage but I made some mistakes:
I added a new project. Unfortunately I chose "Console Application" instead of "Class Library". I tried to fix it by changing it back to "Class Library" in "Project Settings"
I used Nuget to Install-Package WindowsAzure.Storage but I installed it on the MVC project and not on the class library. I tried to fix it by doing Uninstall-Package on the MVC project and installing it to the correct project
I called the class in the class library "WorkOrderStorage"
I added the connectionString to <connectionStrings> element in web.config and a transformation in web.release.config
I guess my project was now in an inconsistent state. I noticed that it would forget about Code First Migrations (I monitored the changes to the .pubxml file):
when I put a reference between the MVC project and the library
containing the WorkOrderStorage class
when I created an empty 'WorkOrderStorage' class in one of the existing libraries
In the end I fixed it by recreating this library correctly from scratch as a class library (because of observation 1). I also named the class WorkOrderRepository (because of observation 2).

Related

Migrations and configuration.seed not running on Azure deployment

I am on EF, with a standard code first DbContext.
public class MyContext : DbContext {}
My seed method in Configuration.cs runs fine locally, when I do an 'Update-Database'
But when I deploy to an Azure Web App instance, none of my seed data shows up. My initial migration runs, but when I add a new migration and publish, it does not get run. So basically only my Initial migration is showing up, and no seed data.
If I check 'Update database', the publish just hangs indefinitely.
I have read that there is supposed to be an 'Execute code first migrations' checkbox, but I don't seem to have that checkbox. I have tried cleaning my project, and restarting VS2013update4. Rebuilding the project, etc. Nothing makes it show up. I have also tried this: http://www.dominicstpierre.com/2012/11/enable-code-first-migrations-check-box.html, but it doesn't seem to work with VS2013u4.
Migrations are in my MyProject.DataLayer project. The actual web app is in MyProject.WebApp. Will this matter? It works fine locally.
What can I do to get this checkbox to show up?
Entity Framework sets up an initialiser on the target machine web.config
This initialiser is run when your app hits the database for the first time.
Here is a link to a good article on the asp.net site that explains how to achieve this: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application
I had the same issue, the seed would simply not get executed after an azure deployment.
I fixed this by adding this to the entityFramework element in the web.config:
<entityFramework>
<!-- excluded other settings for brievity... -->
<contexts>
<context type="WebApplication.Data.ApplicationDbContext, WebApplication" disableDatabaseInitialization="false" >
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[WebApplication.Data.ApplicationDbContext, WebApplication], [WebApplication.Migrations.Configuration, WebApplication, Version=1.0.0.0, Culture=neutral]], EntityFramework" />
</context>
</contexts>
</entityFramework>
It is important that the namespaces are correct for ApplicationDbContext and Configuration, otherwise it will not work.

System.Resources.MissingManifestResourceException when Updating database

I moved a web application I am working on from one machine to another. It is built using .Net MVC and Entity Framework but when I execute the Update-Database command so that the database is updated, I get this error:
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "NameofMigration.resources" was correctly embedded or linked into assembly "NameofProject" at compile time, or that all the satellite assemblies required are loadable and fully signed.
Does anyone know how to fix this error?
I had a similar issue when the resx part of the migration was not included in the project file when a fellow developer checked the project in (probably due to a merge issue). You may find that the resx file is there but greyed out. If it's there, try right clicking the "NameofMigration.resx" file and selecting "include in project". If it's not there, you better go find it on the other machine and add it to the project :-)
I think the issue (one issue) is that the .resx file is added as "dependent upon" (nested under) the .cs file, and the way the build engine works, "dependent upon" changes the name that an embedded resource is saved with (something like, it changes from being based on the filename to being based on the type name; I've dealt with this in other scenarios but can't remember for sure).
This leads to problems when using SDK .csproj files, for some reason (I guess that by default SDK .csproj does not change the resource name in this situation, but the migrations system expects it to).
As someone else had posted, SDK .csproj can use the following tag to change the embedded resource naming scheme for "dependent upon" resources, which then allows the migrations system to find the embedded resource:
<EmbeddedResourceUseDependentUponConvention>
true
</EmbeddedResourceUseDependentUponConvention>
This should go in a <PropertyGroup> of your SDK .csproj file.
For VS 2017, the solution is as follows:
Go to the project file, and for all of the migrations, apply the following format:
<Compile Include="Migrations\201804251606403_emailsWithEffort.cs" />
<Compile Include="Migrations\201804251606403_emailsWithEffort.Designer.cs">
<DependentUpon>201804251606403_emailsWithEffort.cs</DependentUpon>
</Compile>
<EmbeddedResource Include="Migrations\201804251606403_emailsWithEffort.resx">
<DependentUpon>201804251606403_emailsWithEffort.cs</DependentUpon>
</EmbeddedResource>
I guess that the problem is when changing version(s) of Visual Studio, old format of describing dependencies stays, and the Visual Studio 2017 can not interpret it correctly.
Hence, applying the format as described above (change your format to this), you can make the Visual Studio get the idea of where it's resources are.
Slightly different situation, where I created a new environment, and database, and received the above error message.
For my fix, I had to right-click on the migration files (initial and resx) and set property to embedded as resource. Update-database command ran fine afterward.
I encountered the same issue (VS 2017) and none of the solutions provided here worked. I fixed the problem by cleaning the solution and manually deleting the bin folder and then building it again.
If anybody wants to look into the source or compiler to know why this is happening; I don't feel like it right now. After an hour of tinkering, my resolution is odd.
Granted, I shouldn't have done this in the first place, but for quick code I temporarily added classes into the same file as my generated DbMigration 201906212110305_initial.cs. The mere existence of those temporary classes in the same file caused this error. As soon as I moved them to their own file (which I was going to do all along anyway) the runtime error vanished.
Unloading and then reloading migration file worked for me!

add-migration causing a "Could not load assembly" error

Here's what I am looking at
PM> Add-Migration AddedSubdivion -StartUpProjectName Data -Verbose
Using StartUp project 'Data'.
Using NuGet project 'Registry'.
Could not load assembly 'Registry'. (If you are using Code First Migrations inside
Visual Studio this can happen if the startUp project for your solution does not
reference the project that contains your migrations. You can either change the startUp
project for your solution or use the -StartUpProjectName parameter.)
I have no idea why it's trying to reference the Registry project. Registry depends on Data, not the other way around. I am very new to this, so I'd appreciate any help.
This is embarrassing, but maybe this will help out a googler in the future.
At the top of the "Package Manager Console" my default project was set to the wrong project. Changing that to my models project fixed it.
This can also be caused by a platform mismatch between .NET Core and your project. You get the error:
Could not load assembly 'DataProject'. Ensure it is referenced by the startup project 'ProgramProject'.
even though you have specified correct project and startup project names. (Either by using the drop down boxes in VS and the Package Manager Console, or by using the -project and -startupproject parameters.)
You can fix it by switching to Any CPU instead of x86, or vice-versa (or maybe to x64, etc.), but then you will have to switch back and forth every time you need to make changes to your model/DB.
As per this answer you can fix this by changing the order of your .NET Core path entries in system environment variables. If you're getting this error, then it means that either the first .NET Core path is for x64 but you're trying to make changes to your x86 project, or possibly other way around. Move the one you're targeting above the one you're not targeting, save, and then restart Visual Studio.
You can see which one is currently being used with the command dotnet --info.
(Note that this assumes you've installed both. You may also only have one of them installed, in which case you'd need to install the other one, and then check the order of the PATH entries; if the second one you installed is the one you want, then you will definitely need to change the PATH order to make it the one used by VS, since its entry should be at the bottom.)
The problem might not be so obvious if you have Package Manager Console docked with a narrow window...hiding the default project.
Its needs a wide docking.
If all fails there's always the verbose flag (-v).
A command like dotnet ef database update -v should help clarify the problem ef is facing.
In my case, the issue stemmed from EntityFramework finding it difficult to deal with the fact that my platform target was changed from AnyCPU to x86 or x64.
System.BadImageFormatException: Could not load file or assembly 'MyProject, Culture=neutral, PublicKeyToken=null'. An attempt was made to load a program with an incorrect format.
Temporarily changing the platform target to AnyCPU worked just fine.
Make sure that you are focused on:
1- Startup Projects is UI (MVC, API, ... etc).
2- Default project in package manager console is place of (ApplicationDbContext).
I would like to add, if you are using .net6 preview, you will need to update the packages.
so you will need to use the preview versions EntityFrameworkCore.Tools and EntityFrameworkCore.SqlServer (6.0.0-rc-1.21452.10 version as of today)
I had this exact problem, and it turned out because I createdthe project under a blank solution and then added the class libraies and web app seperately it didnt have a start up project.
None of these worked for me. I temporarily unloaded the unrelated project from the solution, ran the command, and then loaded the project back in.
I've got this issue migrating an Asp.Net 5 to Asp.Net 6.
The problema was in the .csproj file.
This configuration
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
I've just removed this property group and the dotnet ef worked
This can also be caused by a platform mismatch between .NET Core and
Also check this in your packages
if don't have that package Dependency Injection
Its very simple you have to install dependency injection package
The package manager window has a Default Project Property.
Setting the default project in the package manager window fixed this for me.
I also had to set the startup project to the same application in the solution explorer.
You should define 2 constructor and OnConfiguring method in context.cs. And also in your UI layer you should define connection string.
Like this:
In Context.cs :
public Context()
{
}
public Context(DbContextOptions<Context> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder
optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Data Source=..");
}
}
In appsetting.json:
"ConnectionStrings": {
"SqlServer": "Data Source=....."
}
In Program.cs:
builder.Services.AddDbContext<Context>(opt =>
{
opt.UseSqlServer(builder.Configuration.GetConnectionString("SqlServer"));
});
Set the target project for the migration as the startup project and continue

Code-First Migrations MissingManifestResourceException

I am currently working on creating the InitialCreate migration for a new database. I am new to this migration framework and do not know exactly what it generates, I have been running update-database to see the result, dropping the database then running update-database again after making some changes to see the results.
Twice now I have made some changes, went to run the update and gotten an error like this:
Applying code-based migration: 201209121936571_InitialCreate.
System.Resources.MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "$assemblyName$.resources" was correctly embedded or linked into assembly "$assemblyName$" at compile time, or that all the satellite assemblies required are loadable and fully signed.
at [StackTrace]
Then it ends in red with
Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "$assemblyName$.Migrations.InitialCreate.resources" was correctly embedded or linked into assembly "$assemblyName$" at compile time, or that all the satellite assemblies required are loadable and fully signed.
The first time I encountered this I dropped the migration folder, ran enable-migrations re-made my changes and was able to run the migration.
It has happened again and I am not wanting to have to recreate the files every time this happens. Does anyone know how to correct this to make the migration work again?
For me solution was to add folowing code in .csproj file of my projected, inside <PropertyGroup>
<EmbeddedResourceUseDependentUponConvention>true</EmbeddedResourceUseDependentUponConvention>
Afted that Update-Database command worked fine.
I ended up figuring this our in the course of pulling together all the information I wanted for asking the question. Namely, trying to reproduce the issue.
It turns out that if you have a class other than the inheritor of DbMigration as the first class in the file, the Resource file takes the name of the other class and not the migration which breaks the migration.
I have filed a bug report here.
I have the problem with Entity Migration, Entity 6.4 and with Microsoft.Net.SDK style project in Full .Net Framework.
I resolved it by editing my Data project with :
<ItemGroup>
<EmbeddedResource Update="**\*.resx">
<DependentUpon>$([System.String]::Copy('%(FileName)')).cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>

Entity Framework Code First Data Migrations not working with VS2012 Web Deploy

I have created an MVC 3.0 application using Visual Studio 2012, .NET 4.5 and Entity Framework 5.0.
Using Code First Data Migrations, I am able to correctly propagate model changes to my local test database, but I can't figure out how to get this to work when deploying to my staging and production servers using Web Deploy.
I have read the following article ...
http://msdn.microsoft.com/en-us/library/dd394698(v=vs.110)#dbdacfx
... which explains what's supposed to happen, but it's not working for me, as Web Deploy seems unable to detect that I am using Entity Framework. The tutorial shows a checkbox to enable execution of Code First Migrations ...
... but my dialog shows the only Update Database checkbox for each database.
I have read that, in order for Visual Studio to detect the use of an Entity Framework context, the Web.config must include an element that defines it. Here's mine:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<contexts>
<context type="MyContext, MyAssembly">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[MyContext, MyAssembly], [MyConfig, MyAssembly]], EntityFramework">
<parameters>
<parameter value="MyConnectionStringName"/>
</parameters>
</databaseInitializer>
</context>
</contexts>
</entityFramework>
Any suggestions would be greatly appreciated.
Thanks,
Tim
I have discovered the solution to this problem through experimentation.
In fact, my MVC application was created by VS2012 by converting from a VS2010 solution. Since the conversion process did not report any issues, I assumed that it had correctly converted everything, including the publishing profiles.
However, I discovered that the problem was in the conversion of these profiles and, unless I manually edit their XML files, there is apparently no way to get old imported profiles to participate in Code First Migrations.
Simply creating new publishing profiles in the converted solution results in the expected behavior.
Try this:
Enable-Migrations -Force
Ensure the below is set to true
AutomaticMigrationsEnabled = true;
Republish - worked for me