I prefer to use DB first approach with Entity framework as many do. In this scenario when the underlying DB schema has changed I just re-scaffold everything by running dotnet ef Scaffold-DbContext with the -force parameter set. When set this parameter causes Entity Framework to overwrite existing files which is want you want as you need your DBContext and model classes to be updated to take account of your new column, table etc. What you don’t want is to lose any custom code you may have had in these classes each time you re-generate the code from your DB. Simple solution here is to use partial classes and/or inheritance.
As an example below.. I often want to see the SQL which EF is generating and in core we can set this up in the OnConfiguring method in the DBContext class. This class will get rebuilt every time you scaffold so you can just inherit from it and then instantiate and use the static non autogenerated one in your app.
Another example might be that you want to have derived properties which are based on one or more properties in one of your auto-generated model classes. Again if you put these directly into the auto-generated model classes you will have to re-do them every time you re-scaffold. In this instance we can use partial classes. Below we see first the auto-generated Students class and then second a manually created partial class which adds a property called FullName. As long as both are in the same namespace .net will put them together.
2 thoughts on “Run Scaffold DBContext without overwriting custom code in Entity Framework core.”