11

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.

M_Idrees
  • 2,080
  • 2
  • 23
  • 53
  • 1
    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. – Chris Pratt Nov 20 '19 at 16:24
  • Thanks @ChrisPratt, Same command did the job, just with extra parameter "-f " as mentioned in Julian's answer. – M_Idrees Nov 21 '19 at 08:00

2 Answers2

11

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
Julián
  • 1,238
  • 1
  • 12
  • 24
  • 3
    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 property for only one particular table. It removes remaining properties for other tables. – M_Idrees Nov 21 '19 at 07:40
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.

MiguelSlv
  • 14,067
  • 15
  • 102
  • 169