Entity Framework Core Tips
A class inheriting DbContext
is needed.
Seeding
One way is to override OnModelCreating
method of DbContext
:
Downside of this is that we need to manually type the ids. Another way is to create seperate class for seeding:
Then, we can run it from Program
of our application:
Ids are generated automatically. Example above also shows how to run migrations on every application startup.
SQLite
It’s good idea to use Sqlite in a prototype. It’s files based DB. Registering DbContext:
The GetConnectionStrings
method is just looking for ConnectionStrings
section in appsettings.json
. Exemplary appsettings.json
:
reactivities.db
is the name of SQLite DB file.
Async
It’s a good idea to get data using async methods, i.e.:
Adding records
DbSet
has an asynchronous AddAsync
method. However, it should be used only
in cases where value generators are used. It’s adviced to use Add
(synchronous
method) in other cases.
DB modification success
It’s a good idea to use the following strategy for finding out if saving changes in DB was successful:
SaveChangesAsync
returns a number of changes done in DB.
Global Filters
Global query filters might be useful when using soft-deletes to filter out the deleted entities by default.
ASP.NET Core
Responses
It’s not the best idea to directly return entities of our DbSet
s. We should
define DTO classes (records) that will contain responses of our API actions.
Returning DB entities directly exposes the whole database structure, which might
bring too many information to the client. Additionally, when Include
ing
relations, we might encounter cyclic references issue when serializing data.