Entity Framework Core Tips
A class inheriting
DbContext is needed.
One way is to override
OnModelCreating method of
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.
It’s good idea to use Sqlite in a prototype. It’s files based DB. Registering DbContext:
GetConnectionStrings method is just looking for
reactivities.db is the name of SQLite DB file.
It’s a good idea to get data using async methods, i.e.:
DbSet has an asynchronous
AddAsync method. However, it should be used only
in cases where value generators are used. It’s adviced to use
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 query filters might be useful when using soft-deletes to filter out the deleted entities by default.
It’s not the best idea to directly return entities of our
DbSets. 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
relations, we might encounter cyclic references issue when serializing data.