Quick Notes: EF Core Scaffolding (Reverse Engineering)
Just quick guide on Reverse Engineering project models from tables
Basic Usage
- install Microsoft.EntitFrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.Tools, and Microsoft.EntityFrameworkCore.Design.
- Run your scaffold command from the PMC
Scaffold-DbContext 'Server=DbServer;Database=DbName;TrustServerCertificate=True;User=UserName;Password=pword' Microsoft.EntityFrameworkCore.SqlServer -Tables Table1, Table2 -ContextDir Infrastructure -OutputDir MyModels- Move your connection string from the dbcontext created from the scaffolding into something a little more secure and less likely to get pushed to repository.
Here's a not so fun little headache. If you forget to create a key in your table before the scaffolding process, it will create the table as a read only class and the class will have the "entity.hasnokey()" property builder as mentioned below. In this case, using something like datacontext.modelName.Add(objectToAdd) will not throw an error but will simply return from that statement as state changes aren't tracked in read only context. Any datacontext.SaveChanges() you may have after that never get called. To fix the issue, put the key in your DB Table, and then modify the on building function for your scaffolded class by removing the .hasnokey() statement (but leave the totable statement).
More info: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/?tabs=vs
Read Only Table/View
- First line of defense is to use read-only credentials.
- Perform the scaffold as usual (tooling doesn't know its read only even if credentials are read only)
- Adjust dbcontext with entity.hasnokey(); declaration in the model building.