Entity Framework Core Database-First Update after initial Scaffold?

ef-database-first entity-framework entity-framework-core


I'm playing around with Entity Framework Core and I have been working on implementing a Database-First application. The initial Scaffold-DbContext command works just fine and creates all my entities correctly, if not organized as I would like. It's a SQL Server database that uses schemas to break up areas of responsibility and I don't really care for the fact that the Scaffold just throws them all into a single folder.

That aside, I have been unable to determine if there is a way to re-run the Scaffold to update the classes after a database update has occurred. The closest I can find is to re-run the Scaffold-DbContext command with the -force parameter. However, this also overwrites any custom code I have added to the Context.cs file, like pointing the connection string to a config value instead of hard-coding.

I have looked at a couple other questions similiar to this one, but it only talks about the initial scaffold, not further updates.

Is there a way short of manually coding any future changes to do this? Without that it seems to make a database-first approach utterly worthless with EF Core.

5/23/2017 11:47:08 AM

Accepted Answer

Like you said yourself... The main problem with database first approach : You should never change the model manually and start renaming things etc. Except if you are 100 % sure that your database won't change anymore. If you'r not 100 % sure, just code with the model that has been auto-generated.

Re-Scaffolding will overwrite any changes made directly in the model class, erasing all what you have changed or added.

But you can make partial classes on the side that won't be overwritten by auto mapping :

public partial class TableName
    public string Name_of_a_property
    {get; set;}

It's a nice way to add code to your entity while being sure it won't be touched by auto-mapping. Just make sure the partial view has the same name as the auto-generated class and everything should be OK.

6/17/2019 1:32:28 PM

Popular Answer

Re-runnable scaffold can be used for true DB First approach as answered by Antoine Pelletier.

However more often scaffold is used once for initial import of the model to your code, and then continue with the Code First approach. The process to use reverse engineering to create an Entity Framework model based on an existing database described in https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow