Entity Framework migration issue - c#

I am using Entity framework and code first approach in my project. I have done some Migrations to my server database and it was working fine. now I added a few more tables and try to create a migration by add-migration command to the database on server.
The command runs with no error and created a migration file.
But, when I check the migration file the code in the migration file was to create all tables again to database (create table for already created tables are also in the up method).
When I run Update-database command it returned an error saying
...table already exist in database.
I try it on some local database on my system and it was working fine.
Can anyone help me with this?
Is there any special permission to set in the server?
Is it because some services from visual studio getting blocked? If so how can I solve it?

Related

Entity Framework trying to add migration of tables that are already in database

When trying to run my ASP.NET MVC application locally, everything works fine. But once I've deployed it Azure, it keeps giving me the error:
Unable to update database to match the current model because there are pending changes and automatic migration is disabled.
So I connected to the remote database using the Package Manager Console in Visual Studio and ran the Update-Database command. This gave me the same error. When I look at the database inside the SQL Server Management Studio, it looks like all migrations are applied.
So after this I tried running Add-Migration to see if there were any changes I didn't notice. The migration it created was exactly the same as the previous two migration (there is nothing in there that's not in one of those migrations).
So far the site ran just fine for about two weeks, including a few migrations. I'm at a loss as to how to solve this, so any help is appreciated.
I'm certain I'm connecting to the right database, because I see it change when I update it to a target migration. I'm also targeting the correct project.
If you are sure that the Add-Migration is creating the script for changes that are already applied, you need to update the migration state of your database. You can do this by adding an empty migration. This will capture the state of your current model.
Add-Migration MergeChanges –IgnoreChanges
After running this command you will have an empty migration script. Now you can update your database to match the model state. Since the actual migration doesn’t contain any changes, it will simply add a row to the __MigrationsHistory table indicating that this migration has already been applied.
NOTE Run this only if you do not have any pending changes and yet you see the error message to update the database.

Code-first migration error

I built my MVC C# based project using code first on local SQL Server and it all worked perfectly fine.
I decided to copy my intire project to a DOK and then paste it on my other computer - I literally did copy to the DOK and paste from the DOK to the other computer desktop.
Then I ran the project and got the followind exception when I try to access one of the models using LINQ:
The model backing the 'BookStoreModel' context has changed since the database was created. Consider using Code First Migrations to update the database
I tried doing update-database -force yet I got there another error:
Cannot find the object "dbo.Customers" because it does not exist or you do not have permissions.
How can it be? The project is running perfectly fine on the original developing machine.
1) Delete All the migrations inside of the 'Migrations' folder
2) Delete all the tables in the database or delete database and recreate
3) Now goto package manager console and create new migration using Add-Migration
4) Then update database using Update-Database command

EF code-first migration via web deploy package not working

I have a WebApi2 project that I'm deploying to my development server via a web deploy package. I used the WebApi scaffolding with MVC, and did successfully create an initial migration for the user-related tables.
Everything worked fine until I accidentally added a controller with EF & actions, using the wrong model. I deleted the controller, but something must have been created by EF behind the scenes, because now every time I try to access the Api I get the following error:
The model backing the 'ApplicationDbContext' context has changed since the database was created.
Consider using Code First Migrations to update the database.
I looked at the Migrations folder, but there are no changes in there.
I checked my source control, but I can't see any changes in there, either.
I have tried setting AutomaticMigrationsEnabled = true in my configuration class, but that didn't seem to do anything at all.
I tried calling Update-Database from the package manager console, but that's looking for the Db in the App_Data directory, whereas the correct Db is hosted on my local instance of SQL Server, so that failed.
I even tried to add a new migration, but that fails with the following error:
Unable to generate an explicit migration because the following explicit migrations are pending: [201603181320388_Initial]
Looking at the database I can see the tables that were created by that migration, so I'm pretty sure that's also due to EF not seeing the correct Db.
I tried changing the connection string in my project's web.config file to the one from the deployed web.config file in an attempt to make EF look at the correct file location, but no joy.
I'm pretty new at using EF, so the answer is probably something obvious, but I can't see it.
Is there maybe a way to see what has been changed in EF and undo it? Or can I specify the path to the database for the Update-Database command?

Migration error if code first approach is used for the first time

I my MVC 5 project I used code first approach for creating the database. However after enable migration, I am getting error
Migrations is enabled for context 'ApplicationDbContext' but the database does not exist or contains no mapped tables. Use Migrations
to create the database and its tables, for example by running the
'Update-Database' command from the Package Manager Console.
However if i delete migration folder then error is resolved but then I an unable to use migration. Please help. I am attaching screen shot for the error.
I run the command for add-migration and then update-database. That did help me. But if i change connection string and run the project again then it is not creating database until migration folder is not deleted.
Before you can use your database, you need to create a migration, that describes structure of your database with the Add-Migration command and then update your database to match you current model with the Update-Database command.
You might find this tutorial useful.
Enable migrations just creates scripts for creating and seeding that database. You need to run update-database from the package manager console to create the database. The database will be created on the server referenced in your web.config connection strings

There is already an object named '__MigrationHistory' in the database

When I tried to execute SQLQuery (generated by Update-Database -Verbose -f -Script locally in Visual Studio) on remote database, I see the following error returned by SQL Server Management Studio:
Msg 2714, Level 16, State 6, Line 1
There is already an object named '__MigrationHistory' in the database.
How to solve this?
Just a question. Are you using a different schema other than dbo?
I think its a bug in EF framework where it doesn't check the schema when it does it checks to see if the __MigrationHistory table exists.
I was able to solve this problem by just creating a Dummy __MigrationHistory table with the dbo schema, this tricked the EF6 generator for "creating the table"
CREATE TABLE [dbo].[__MigrationHistory] (
[MigrationId] [nvarchar](150) NOT NULL,
[ContextKey] [nvarchar](300) NOT NULL,
[Model] [varbinary](max) NOT NULL,
[ProductVersion] [nvarchar](32) NOT NULL,
CONSTRAINT [PK_dbo.__MigrationHistory] PRIMARY KEY ([MigrationId], [ContextKey])
)
If you want to automate it, you'll have to create a Empty Migration with a dummy class that uses the dbo schema and run that migration first to generate the relevant tables. Then run the scripts for the migration with the different schema and it should work.
__MigrationHistory is an auto-generated table used by EF to track what upgrades/patches it has applied to the database. EF is completely aware of that table and handles it on its own. You should ot create/drop/alter that table. It seems your database already has that table. If EF or your upgrade-script tries to create such table, this is strange. You need to carefully review everything and guess/learn what really has happened, because either EF went wild, or your scripts are prepared in a wrong way.
I've seen this happen when doing "Code First from an Existing Database" where the database being pulled from already has __MigrationHistory table.
It ends up added a POCO class of the type. Remove the class, redo migrations and run again.
You should either change your connection string of your startup project to point to the remote database - it would appear that it is pointing to a database that already has a __MigrationHistory table, or generate a full script using
update-database -script -SourceMigration $InitialDatabase
which will script all migrations into a single file and check migration by migration to see which ones it needs to run. The first thing this script does is check for the existence of __MigrationHistory table and create it if it doesn't exist.
A setup for a migration might be missing. Typing the command add-migration MigrationName in the Package Manager Console before updating the database worked for me, as suggested in this tutorial
Change database name in the connection string in web.config solved to me after drop database. It's a workaround that helps in dev environments. The db was recreated with the new entities.
I opened SQL Explorer from visual studio and connected to the database. Dropped table using SQL directly. Deleted Migrations folder. Ran migrations again. As it is test database, there was no big issue in dropping table. If it has data, you need to think of a different solution. Nothing else worked.
Tools > SQL Server > New Query
drop table "table_name";
Solution Explorer > Right click on Migrations and Delete
Tools > Nuget package manager > Package manager console
In the Package Manager Console (typically opens at bottom of screen): Add-Migration InitialCreate4
Update-Database
If you are using an existing database with EF and .net core then as of writing you will need to create an initial migration (dotnet ef database update) with empty Up/Down methods (manually delete the code) as -IgnoreChanges is not implemented:
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
This will prevent your migration from attempting to create the tables as is normal on a first migration in a code first scenario.
Run
dotnet ef database update
Once complete you will be able to update using normal migrations.
See:
https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/existing-database
And
What is the equivalent of the -IgnoreChanges switch for entity-framework core in CLI?
Go to Migration Folder.
You will see two files one is the configuration and the other file starts with some number like 019763632... open it
comment the code which Generates the already created table. and then enable automatic Migration Enable-Migrations -EnableAutomaticMigrations
The update-database
This worked for me try it
I managed to solve this error by removing the part where I make sure the database is created.
//Database.EnsureCreated();
This part is supposed to create the database if it did not exist only.

Categories