Deleted migration files and can't create new database model from scratch - entity-framework

I'm trying to reset my database, I deleted all migration files but now when I create a migration it doesn't include anything in the Up(), no create tables, keys etc. I've rebuilt the solution and restarted Visual Studio and it still doesn't work.
I'm using model builder with code first to define table relationships.

You also need to delete the {contextname}Snapshot.cs
In your .csproj file there must also be referenced that you removed the migration.
...
<ItemGroup>
<Compile Remove="Migrations\xxxxxxxxxxxxxxxxxxxx.cs" />
</ItemGroup>
...
I suggest you take the cli from entity framework -> remove-migration migrationName

Related

How to remove a migration manually in EF core 6 (I don't have the Migrations/ts_migrationfile.cs)?

I'm having trouble with a migration that seems to have been wrongly deleted by EF core.
It says I have to manually delete some file, since the migration file was not found, but I can't find a guide on how I'm supposed to delete that.
I had my initial create migration
I added a new one for creating a couple more columns in a table
I didn't realize that mi project was set to pgsql instead of sqlite
I deleted the migration (never applied database update)
Ef core delete command deleted the migration files on ./Data/Migrations
I set sqlite
I added a new migration
The new migration was on pgsql again
Delete migration tries to delete the (step 2) migration instead of (step 6) migration and fails.
It says No file named '20220308_Migration2.cs' was found. You must manually remove the migration class 'Migration2', hence the question.
My commands for adding and removing and listing the migrations were the followings:
dotnet ef migrations add name -c MyContext -p .\Project.Db\Project.Db.csproj -o .Project.Db\Data\Migrations -s .\Project.Server\Project.Server.csproj
dotnet ef migrations delete name -c MyContext -p .\Project.Db\Project.Db.csproj -s .\Project.Server\Project.Server.csproj
dotnet ef migrations delete name -c MyContext -p .\Project.Db\Project.Db.csproj -s .\Project.Server\Project.Server.csproj
After all done, if I execute the list command, output shows:
Migration1 (pending)
Migration2 (pending)
Where Migration1 is the initial create and Migration2 is the migration applied on step2.
The files I have on Data/Migrations folder are the ones corresponding to Migration1 and Migration3 (step 6)
Another questions.
Where does the list command data comes from? is there a secret database or a hidden caché folder?
If I just delete the Data/Migrations folder, will I be able to start over with the migrations?
Thanks
My problem was on communication between projects. I failed to mention before that I have my solution splitted between projects (as you can see by the commands), and happens that those projects are linked to each other by hard links (Microsoft's mklink -h) to de .dll of the compiled lower layer project.
What happened was that somehow the hardlink between the DB project and the Server project failed, so the Server project was not aware about the changes on the Db project, and it could only see the DB project as it was at the moments the hard link failed.
I finally deleted the reference and added it again. As soon as I did that, the project recognized the real state of the migrations and everything went smoothly.
So (answering my questions), the message was telling me to delete the migration file in ./Data/Migrations. The file was deleted, but the Server project could not see that.
The "cache" was actually the broken hard-link that referenced an old version of the DB project. The list command scans the folder -/Data/Migrations and compares with the database.

Updating database to Migration Configuration

I have pulled down a Visual Studio 2015 project created my another developer. Within the Migrations folder are several Migration Configuration files ...
201601081315335_AddedPersonEntities.cs
201601091532275_AddedDepartmentEntities.cs
201601101145137_AddedPayrollEntities.cs
I would like to update my database to the point of one of these Migration Configurations. However when I try this command ...
Update-Database -Verbose -StartupProjectName MyApp.Api -ProjectName MyApp.Data -ConfigurationTypeName 201601091532275_AddedDepartmentEntities.cs
I get the following error ...
The migrations configuration type '201601091532275_AddedDepartmentEntities' was not be found in the assembly 'MyApp.Data'.
I was expecting it would bring my database up to the same schema at the point that 201601091532275_AddedDepartmentEntities was created. Am I missing something?
Go to visual studio, select your MyApp.Data and check the "Show All Files".
Inside the migrations folder, see if there aren't migrations "outside" the project. If there is, then add them to the project with Right-Click > Include in project.
Do you use TFS?
It happens when you add something (File/Folder) inside a project in your solution and check-in your solution, and your colleague doesn't do correctly the merge on the .csproj file (Which contains all the information about the files and folders inside the project).
WAIT
Ok i think this isn't the problem.
You are specifying -ConfigurationTypeName: don't you want -target: instead?
-ConfigurationTypeName Is used to define the configuration class (Normally contains the seed method).
-target Specifies to where you want to update your database (From the current migration to that specific one, forward or backwards it works anyway).
And, do you insert the models inside MyApp.Data or MyApp.Models?

Can't Get Code First Automatic Migration to Work On Existing SQL Server CE Database

Summary:
I'll start with the summary and then follow with the details. For my project, automatic migration is not happening on the live .sdf database file in the working directory. It's as if that .sdf file didn't exist. Instead, all configuration actions are performed on a new, empty database file which it creates on in the Program Files/Microsoft Visual Studio 10.0/Common7/IDE directory. How do I get it to work on my live .sdf database file in the working directory?
Details:
The project uses Code First EF in Visual Studio 2010 Ultimate. The project was started with EF 4.1, and I just updated the project to EF 4.4.
The database file is a SQL Server Compact Edition 4.0 file, which is located in the same directory as the executable (i.e., the working directory). Everything has been working fine for some time now, but I want to add two new DbSets to the DbContext, and hence two new tables to the database file. When I deploy the new version of the program to customers, I want the program to seamlessly just add the two new tables to the database, and continue on as if nothing had happened, leaving untouched all the extant data in the other tables.
Attempt 1
Per the process described in http://msdn.microsoft.com/en-US/data/jj554735:
I added to two new DbSets to the DbContext-derived class. When I attempted to run the program, I got the following exception: The model backing the 'DrillContext' context has changed since the database was created. Consider using Code First Migrations to update the database. This is what I expected to happen, since I hadn't yet enabled migrations.
In the Package Management Console I then issued the command:
Enable-Migrations -EnableAutomaticMigrations.
The system created a Migrations directory with a Configuration.cs file in it.
I then ran the
Update-Database
command, and got the message No pending code-based migrations. I checked the live database file in the working directory, and it was unchanged. There was, however, a new database file with the same name in the Program Files/Microsoft Visual Studio 10.0/Common7/IDE directory that had the same name and was an empty database with all the appropriate tables, including the two tables corresponding to the two new DbSets in the DbContext-derived class, and a new table named _MigrationHistory, which has a single entry in it. The live .sdf file remained untouched, without the new tables, and with no _MigrationHistory table.
Attempt 2, which uses an "InitialMigration":
Per http://www.ladislavmrnka.com/2012/03/ef-4-3-migrations-and-existing-database/
To prepare for the second attempt I restored the program's original state (i.e., to the state it was before I attempted the migrations) by doing 3 things. I removed the 2 new DbSets from the DbContext-derived class. I deleted the Migrations directory (and the enclosed Configuration.cs file), and deleted the useless database file (.sdf file) in the ".../Common7/IDE" directory.
I then executed the command:
Enable-Migrations -EnableAutomaticMigrations
which created the Migrations directory and the Configurations.cs file.
I then executed the
Add-Migration InitialMigration -IgnoreChanges
command, which added an 201208281905525_InitialMigration.cs file to the Migrations directory.
Then, per the directions on the cited web page, I modified the Up method in the file so that the InitialMigration class became the following:
public partial class InitialMigration : DbMigration
{
public override void Up()
{
Sql("DROP TABLE EdmMetadata");
}
public override void Down()
{
}
}
I then executed the
Update-Database
command, and got the message The specified table does not exist. I checked the live database in the working directory, and found that there is indeed an EdmMetadata table in the database. I then checked the .../Common7/IDE directory and found that the new database that had been created there did NOT have the table.
So all "migration" activity is occurring on the .../Common7/IDE version of the file but not on the live database file in the working directory.
How do I get it to work on the existing, live database file?
Thanks,

EF 4.3 migrations throwing "Unable to open configSource file"

I'm trying to use EF 4.3 migrations feature. My ASP.NET MVC project stores connection strings in external file:
<connectionStrings configSource="bin\connections.config" />
All runtime procedures (including automatic migrations) work fine. However, no powershell commandlet, connecting to the database, is able to find external file. It throws "Unable to open configSource file" exception. I was trying to place .config file in different places as well as changing configured external file location to no avail. Is there any workaround available?
Update: I've found that EF creates a temporary AppDomain with configuration file located in temp directory. So the only workaround at the moment, it seems, is to place external configuration in the same temp directory. Any other suggestions?
Using EF 6.1 here.
If like me you were linking to a connectionStrings.config file located in another project than your Entity Framework migrations project (using Add as link), you'll probably need to move the file back to this EF project and link to the moved file from the other projects instead...
There are unfortunately no easy way to handle external configSource files with the powershell cmd-lets in EF migrations. I've given up on it and moved the connection strings into the config file for the class library that contains the db code. The alternative is, as you've found out yourself to manually copy the file. Unfortunately the copy process doesn't honor the build settings of the project, so setting the external config file to be copied at build doesn't help.
EF 4.3.1 supports configSource.

Why is the designer creating two .Designer.cs files when updating model from database?

Like the question says: In Visual Studio, when in the Model.edmx, when I Update Model from Database... after adding a few new database fields, it's creating an almost duplicate Model1.Designer.cs file that is causing conflicts with the original Model.Designer.cs.
I can delete the new Model1.Designer.cs file, but then the newly added fields aren't available.
Is there a solution to this (other than deleting and recreating the model)?
It sounds like you might have deleted and recreated the model (or something similar) but left the original designer file in the directory. Then when you added a new model it had to use Model1 instead of Model as the designer file name. Have you tried excluding the Model.Designer.cs file and leaving it working with the Model1.Designer.cs file instead?
Okay, looking at the project file for a project of ours with a model in, I can see the following potentially relevant sections:
<Compile Include="Domain\Model.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Model.edmx</DependentUpon>
</Compile>
I believe this one tells the project that the code file is part of the project, and should be a subnode of the file model.edmx, and be regenerated when it changes.
We also have this section:
<EntityDeploy Include="Domain\Model.edmx">
<Generator>EntityModelCodeGenerator</Generator>
<LastGenOutput>Model.Designer.vb</LastGenOutput>
<CustomToolNamespace>Domain</CustomToolNamespace>
</EntityDeploy>
Not sure which of these controls the generated file name, but you could try hand editing your project file to see if it makes a difference. I'd say you'd need to change both at the same time, rather than just one.
Cause:
I can recreate this (and do by mistake now and then): it occurs trying to save the database diagram (edmx file) while running a project such that Visual Studio cannot write to the various files and generates ones with new names. There may be other ways to recreate it by making the files unavailable for writing. The project will keep working, it just creates a problem for version control and I imagine some deployment models.
Symptoms:
[projectname]Model1.Designer.cs, [projectname]Model2.Designer.vb, etc. files alongside [projectname]Model.Designer.cs, [projectname]Model.Designer.vb files
extra enitity files in form of [entityname]1.vb, [entityname]1.cs such as Person1.vb
project file has references to redundant files such as:
<Compile Include="Models\DataContexts\FooModel.Designer.vb" />
<Compile Include="Models\DataContexts\FooModel1.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>FooModel.edmx</DependentUpon>
</Compile>
project file has reference with Model1.Designer, Model2.Designer etc such as:
<EntityDeploy Include="Models\DataContexts\FooModel.edmx">
<Generator>EntityModelCodeGenerator</Generator>
<LastGenOutput>FooModel1.Designer.vb</LastGenOutput>
</EntityDeploy>
Project file has references to multiple entities or entities with 1.vb or 1.cs in the filename.
<Compile Include="Models\Entities\Person1.vb" />
Project may build and run correctly, but new files may not be in version control.
Remedy
Close Visual Studio
Make a backup of the project folder.
Fix the files:
Go to the folder in the project with the data context files such as Designer.vb, Designer.cs, [projectname]Model.Designer.vb, [projectname]Model.edmx
Keep the most recently modified version of the duplicate files and delete all others.
Rename those files to remove the 1s, 2s, etc from the filenames
For example, if [projectname]Model1.Designer.vb, [projectname]Model2.Designer.vb, [projectname]Model.Designer.vb exist and [projectname]Model2.Designer.vb has the most recent modified date, delete the other to and rename [projectname]Model2.Designer.vb to [projectname]Model.Designer.vb.
Do the same with any other files that have duplicates or 1.vb, 1.cs appended to them.
Fix the project file. Open up the project file with your favorite xml or text editor and fix the following references. (A search for "1.", "Model1", "2.", "Model2." will find these also.)
Change:
<Compile Include="Models\DataContexts\FooModel.Designer.vb" />
<Compile Include="Models\DataContexts\FooModel1.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>FooModel.edmx</DependentUpon>
</Compile>
To:
<Compile Include="Models\DataContexts\FooModel.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>FooModel.edmx</DependentUpon>
</Compile>
Change:
<Compile Include="Models\DataContexts\Person1.vb">
<DependentUpon>Foo.tt</DependentUpon>
</Compile>
To:
<Compile Include="Models\DataContexts\Person1.vb">
<DependentUpon>Foo.tt</DependentUpon>
</Compile>
Change:
<EntityDeploy Include="Models\DataContexts\FooModel.edmx">
<Generator>EntityModelCodeGenerator</Generator>
<LastGenOutput>FooModel1.Designer.vb</LastGenOutput>
</EntityDeploy>
To:
<EntityDeploy Include="Models\DataContexts\FooModel.edmx">
<Generator>EntityModelCodeGenerator</Generator>
<LastGenOutput>FooModel.Designer.vb</LastGenOutput>
</EntityDeploy>
Open up visual studio and all should be well.
This happened to me today, and I solved it by:
Close the edmx editor pane if you have it open.
In the solution explorer, delete the offending designer file.
Save all
Rename the edmx file to a different name (such as 2.edmx)
Save all
Open the edmx file and save it to regenerate the designer file.
In the solution explorer, rename the edmx file back to its original name.
I had the same problem, the model was generating a second designer.cs file. This was after working through a whole bunch of issues with my installation of vs2010 related to the designer (somehow vs2010 lost the references to a bunch of DLL's related to the Data Entity Model designer requiring rededits and reinstalls).
Taking Kevin's advice, I edited the project file manually to point to my preferred file and it worked. The designer stopped recreating the second file.
If you are using any version control utils like SVN, the easiest way to fix it is to compare working copy with previous revisions and revert one line in .csproj where designer name changed to that with '1' suffix.
This has been reported to Microsoft, but they haven't been able to reproduce it.
See https://connect.microsoft.com/VisualStudio/feedback/details/532800/msdatasetgenerator-create-another-designer1-cs-file-for-my-typed-dataset
Had the same issue, and none of the older answers worked for me. The extra designer kept re-appearing.
My Cause (in the .csproj):
<Compile Include="DAL\MyDataSet.cs">
<DependentUpon>MyDataSet.xsd</DependentUpon>
<SubType>Component</SubType>
</Compile>
Solution:
<Compile Include="DAL\MyDataSet.cs">
<DependentUpon>MyDataSet.xsd</DependentUpon>
</Compile>
The extra SubType caused MSDataSetGenerator to run twice each time. After removing the subtype, you will still need to delete any other erroneously generated MyDataSet1.Designer.cs entries. See Kevin's post for a couple of examples.