CodeFirst Approach.
I have a multi project solution.
My Projects are structured by. AccessService, ModelService and the ProjectName for the razorpages and rest of the code.
TestDb: I have an existing database and Migration called TestDb. I want to update my Migration then Update the database for any edit or new models which the db needs to save.
The a migration has multple models in the table, Student is one of them. The Table Student has: Student Id student name, I want to add StudentGrade to the Student table. So the table Student has a new field Grade. Another example would be. I want to add the Model Class Room. It does not exist in the original migration or db. I want to add it to the DB so it holds a new table ClassRoom.
I have FramewWorkCore.tools(6.0.13), same version for sqlServer.
When i use these commands i just get errors.
I've tried Force, IgnoreChanges and f.
I solved one large problem.
Now i got another.
Your target project 'ProjectPortal' doesn't match your migrations assembly 'ProjectAccessService'. Either change your target project or change your migrations assembly.
Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("ProjectPortal")). By default, the migrations assembly is the assembly containing the DbContext.
Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project.
So my understanding is, i need to somehow tell entityframework to change the target to AccessService
Here's the solution. This is meant for multiple projekts.
If you have an AccessService and a AllProjekt like i do,
You need to add this.
builder.Services.AddDbContext<DbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("AuthConnectionString"),
b => b.MigrationsAssembly("ProjektAccessService")));
ProjektAccessService is the name of your Solution/projekt.
You do not start a Migration before adding this. If your migratet your before adding this, i can't help you.
I added this, then i started my first Migration. Updated the database.
Tried my 2nd Migration, updated the database. It works. Is it a solution for all. deferentially not. Is it dumb, 100%.
Related
I'm developing a WPF app utilizing a SQL Server Compact 4.0 database. For the course of this project, we made several changes in the model structure with a number of code-based and later with automatic migrations. They all are stored in the _MigrationHistory table and represented by several migration classes.
Now it appeared that I need to considerably change the model. Since the app is still in the development phase, dropping data in the database is not a concern. I would like to get rid of the whole previous migration history and start a new clean model. So my question is what steps are to remove the whole history of migrations and start a new history with automatic migrations in the future.
What parts of the project must be deleted and how to do it safely?
First Make sure your project is backed up and your database is also backed up. In case something goes wrong.
If your project is setup using entity framework code first,
In the project you can delete all the migration files in the 'Migrations' folder except 'MigrationConfiguration.cs' contained within the project that is using entity framework.
Also if you are not concerned with dropping the database, then go-ahead and delete the entire database, then create a new one with the same name that is configured in your database context connection string found in your project's config file.
Rebuild your solution and create a new migration by typing the command in the package manager console 'add-migration' and provide a name. This will create a new migration to create the database for all your code first models. If the generated migration file looks correct, then run 'update-database' in the package manager to apply the migration to your empty database.
I have two solutions, the base solution with no migrations(which is in production, so I can not wipe the data) and now I have branched of this to set up migrations and make some model changes.
First I need to set up migrations on the branched solution (second solution) so that I can apply the model changes so I:
Turn on migrations which auto creates an InitialMigration
Enable-Migrations -ContextTypeName Context
Make a blank migration based on the suggestion from https://www.apress.com/gp/blog/all-blog-posts/secular-trends-for-the-cloud/12097630
Add-Migration InitialBlank -IgnoreChanges
Update Database * update-database*
Make my model changes
Add a migration containing my model changes * Add-Migration add_entity*
Run Update-Database
So I delete the database created as I need to run the first solution to create the initial db setup (to mimic live).
When I run the first solution it creates an entry in MigrationsHistory table named InitialCreate (201807061432030_InitialCreate), which has been auto created. I then run update-database on the second solution which applies my model changes fine although their are discrepancies in the InitialCreate MigrationId.
Migration entries in my second solution (in order they were created and the order they are in the solution):
- 201807061257015_InitialCreate
- 201807061315294_InitialBlank
- 201807061323086_add_entity
Migration entries in the migration history table after running the first then second solution:
1 | 201807061315294_InitialBlank
2 | 201807061323086_add_entity
3 | 201807061432030_InitialCreate
The second solution runs fine but when I try to add any data I get System.InvalidOperationException: 'The model backing the 'Context' context has changed since the database was created. Consider using Code First Migrations to update the database.
I have tried to create another migration on the second project to make sure their are no model changes that have not been migrated (their shouldn't be) but I get an error.
Unable to generate an explicit migration because the following explicit migrations are pending: [201807061257015_InitialCreate]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
My questions:
How do I resolve the MigrationId mismatch? As the first solution did not have migrations turned on and when I do turn them on (in the second solution) it creates a new id.
Could the exception System.InvalidOperationException: 'The model backing the 'Context' be thrown by the MigrationId mismatch or could anyone point me at why this could be happening? I have had a look into this error but the solution's I found don't seem to work:
Deleting the migrations history table is no good as I can not do this in production because of customer data.
The other solution I found of adding Database.SetInitializer(null); to global.asax seems to make no difference.
Why does the order of my migrations look different once they have been applied in the migration history table?
Thanks in advance!
I am not sure if this will work but I think I may need to manually delete the first InitialCreate and edit the db entries to reflect the correct InitialCreate. Based of this SO question I just found https://stackoverflow.com/a/13108243/3172635.
I will have to try this Monday though.
Edit: I first tried deleting the InitialMigration entry in the _MigrationHistory table but this does not work as it tries to apply the InitialMigrations again but cant as the tables are already created. So what I did was update the MigrationId for the InitialMigration entry to reflect what it was in the new project.
The sql I used:
SET MigrationId='201807061257015_InitialCreate' WHERE MigrationId = '201807061432030_InitialCreate'
I am working on a entity framework project generating the Entity classes using the New-> ADO.NET Entity Data Model -> Code First From Database. I then select nearly 100 tables to generate (not all tables are suitable to go in the model).
Problem is I am regularly updating the schema, and the only way to refresh the model seems to be to delete and start again, which is fine except I have to re-select the nearly 100 tables again.
Is there any easy way of scripting this generation process?
You should look into using Entity Framework Migrations and start doing your schema changes from the code itself
Set the CompanyName.ProjectName.Infrastructure.EfRepository (the project which has your DbContext) as start up project of the solution
Open the Package manager console
Choose CompanyName.ProjectName.Infrastructure.EfRepository as default project
Run the following commands:
Enable-Migrations -ConnectionStringName "EfDataRepository"
Add-Migration Initial -ConnectionStringName "EfDataRepository"
Update-Database -ConnectionStringName "EfDataRepository" -Script -SourceMigration:0
Then delete the auto-generated Migrations folder within the EF project!
Where EfDataRepository is the connection string name.
I'm having some issues updating my database to reflect my model changes using migrations in EF7. At first, I create a model (let's just say Person for example), created an initial migration, and updated my database.
dnx ef migrations add Initial
dnx ef database update
No problems there, everything worked fine. However, now I'm creating another model (let's say "Car") that I also want to create a table for. So I followed the same steps: add a new migration, and try updating my database using dnx like below.
dnx ef migrations add CreateCarTable
dnx ef database update CreateCarTable
This is where I get my problems. Even though I'm specifying the specific migration I want to use, it keeps trying to run all of them, so I'm getting an error complaining that tables already exist (in my case it's the AspNetRoles tables that gets created in the "Initial" migration).
Has anyone had similar problems and/or have a solution to this?
In my main project, I have configured a connection string to my database like this:
<add name="DefaultStoreConnection" "provider....">
In my infrastructure project, I have a database context with a default constructor that passes the connection name to the base class:
public DatabaseContext() : base("DefaultStoreConnection") {}
As soon as my application starts, EF generates a 'store.sdf' (SQLCe database) in the application output folder (\bin).
Now, I wanted to reset all migrations and start with a plain database. I deleted the 'store.sdf' in the \bin directory, deleted all migration files and then called in the Package Manager Console:
Enable-Migrations -Force -ProjectName "MyInfrastructureProject" -StartUpProjectName "MyMainProject".
This worked fine, a new migrations configuration class was generated. Then I ran:
Add-Migration Initial -ProjectName....
And then the following line appears:
A previous migration called 'Initial' was already applied to the target database
Where? Where does this migration has been applied to? Where can I reset this 'migration'?
It should be in a folder containing all the migrations, but it's possible that it's deleted after it has been applied to database. You can see list of applied migrations in __MigrationHistory table of your target database. If you wish to rescaffold the database, empty the __MigrationHistory table.
I run to the same problem as you. After a day of google search without a single useful help, i figured it out myself that this is Visual Studio bug where your solution have more than one Mvc projects. The add-migration will check on the older Mvc project to create migration file for your current project (that is why i call it BUG).
To avoid this, you should only use one Mvc project per solution.
Have a look at the app_data folder of your project.