EF Core 5.0.X - made changes to db now how to update dbcontext?

wavemaster 311 Reputation points
2021-06-04T15:29:02.207+00:00

I have a dbcontext that was a result of scaffolding, now I need to make changes to the db such as adding relationships and deleting some others.

How can I force EF Core to pick up on these changes, but leave everything else untouched?

Developer technologies | .NET | Entity Framework Core
0 comments No comments
{count} votes

Accepted answer
  1. Duane Arnold 3,216 Reputation points
    2021-06-07T07:23:37.387+00:00

    @wavemaster

    See that's a shortcoming with EF Core and model creation is that if you have any customization in the DbContext, you'll lose it all if you Scaffold the DBcontext again based on new changes, and the DBContext being used by the program is overwritten by the new DBcontext.

    What do you do what do you do to prevent DBContext customization from being lost in this situation?

    I have resorted to Scaffolding the output of the Dbcontext to a staging folder in the VS project and done a copy/past operation of what's new in the new dbcontext over to the current DBContext being used by the program.

    What other choice do you have?

    If you don't have customization in the DBcontext, then by all means, just overwrite the DbContext.cs used by the existing project.

    If your Dbcontext is huge, then you could Scaffold output to the staging folder and do a file comparison between the current and new DBContext(s), note the changes and copy/paste code appropriately. Visual Stuido has a file comparison feature you can use.

    https://www.meziantou.net/comparing-files-using-visual-studio-code.htm


1 additional answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,656 Reputation points
    2021-06-07T06:12:33.723+00:00

    Hi wavemaster,
    You can re-scaffold the model by running the command that you originally ran with the -Force option added. That will result in the contents of the specified folder being over-written.
    The code looks like below:

    Scaffold-DbContext "Server=(localdb)\v11.0;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force.  
    

    More details please refer to the following links:
    Entity Framework Core tools reference - Package Manager Console in Visual Studio
    Razor Pages with Entity Framework Core in ASP.NET Core - Tutorial 1 of 8
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.