How to update existing model class generated by Scaffold-DbContext
Asked Answered
A

2

14

Working with ASP.NET CORE EF, I have generated model classes from existing database with following command:

Scaffold-DbContext "Server=myserver\mydb;Database=mydb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Now my database is changed, for example I added a new column in a table AppUser. I don't want to use migrations to keep sync models with database.

I already made changes in database and now I want to update my existing model classes from current database state. Any suggestion how to do this?

Should I delete my existing model classes and regenerate by using the same command Scaffold-DbContext or do we have any other way make existing model classes to reflect new changes.

Agriculturist answered 20/11, 2019 at 11:31 Comment(2)
Yes. In general, every time you change your database, you just re-run Scaffold-DbContext. You should not directly modify any of the entity classes that are generated, as a result.Ebersole
Thanks @ChrisPratt, Same command did the job, just with extra parameter "-f " as mentioned in Julian's answer.Agriculturist
P
16

Are you looking for something like this?

As far as I know, to update the model you must execute the same command to overwrite the changes but with another additional flag.

I remember using the -f (force) option to overwrite the changes:

Scaffold-DbContext "Server=myserver\mydb;Database=mydb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f

Although it is also possible to indicate which entity you want to update (table):

Scaffold-DbContext "Server=myserver\mydb;Database=mydb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -t <table> -f
Piccalilli answered 20/11, 2019 at 13:30 Comment(1)
Thanks @Julian, First command done the job. Second command also works but not as I was expecting. Although it has generated model class for one table but also it overwrites my DbContext class, where it contains DbSet<T> property for only one particular table. It removes remaining properties for other tables.Agriculturist
D
0

Scaffold-DbContext can be used with option -Context to expand the current DbContext file, instead of creating a new one.

Example:

Scaffold-DbContext "Server=server;Database=mydb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f -Context MyDbContext

The generated code for the MyDbContext will be placed on a partial class file.

Deandreadeane answered 18/6, 2021 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.