- Entity Framework Core Docs
- ASP.NET Core Application to Existing Database
- Building REST APIs using ASP.NET Core and Entity Framework Core
Scaffolding from an existing SQL Server db
Follow instructions here: https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html
Scaffold-DbContext "<connection string>" [-Schemas <schema names>] Microsoft.EntityFrameworkCore.SqlServer -Force -OutputDir <dir>
will be created as a subdirectory in the project and used as namespace suffix in the generated model classes.
- The -Force flag is useful when regenerating the models because the models cannot be removed before re-scaffolding (the tool requires that the project can be compiled before scaffolding)
- It’s probably a good practice to generate each schema in your model into a separate output dir, because if there are two tables with the same name in different schemas, the tool just appends ´1´ to the model name.
The context must also be modified each time you regenerate the models:
It is not currently possible to isolate an EF Core solution to a class library: https://docs.efproject.net/en/latest/miscellaneous/cli/dotnet.html#targeting-class-library-projects-is-not-supported
ASP.NET Core APIs
Returning EF model objects directly from ASP.NET Core APIs requires ignoring reference loop handling in JSON serializer settings (
To prevent json serialization from converting from pascal to camel case (to keep your models in sync with e.g. your typescript interfaces), you can override the default contract resolver (DefaultContractResolver is not the default https://github.com/aspnet/Announcements/issues/194):
Note that although this allows rapid development, returning the EF models directly is still probably a bad idea in all but the simplest scenarios: http://juristr.com/blog/2012/10/lessions-learned-dont-expose-ef-entities-to-the-client-directly/
TODO there is no way to prevent JSON serialization from following all relations and unwinding everything into the serialized object => absolutely must use DTOs
Not possible to load related data using relation name as string: https://docs.efproject.net/en/latest/querying/related-data.html. Lazy loading is not supported either.
TODO: separate document for web apis in core https://docs.asp.net/en/latest/tutorials/first-web-api.html