Entity Framework Core
#
IntroductionEntity Framework Core is an object-relational mapper that lets .NET developers work with a database using .NET objects.
This reduces the amount of data-access code that needs to be written.
This means that instead of writing code to directly interact with our databases, we can instead create a domain class which identifies the database from which we’re retrieving our data and maps column titles to the properties of that class.
#
Video TutorialWatch a video version of this page if you prefer!
#
How is it implemented in the Base API?We call
EntityFrameworkCore
within theDatabaseContext.cs
file in the infrastructure namespace.We then create a
DatabaseContext
Class, which inherits methods fromDbContext
- a part of EntityFrameworkCore. If necessary, we can extend the methods in DBContext using an override modifier.The most important part of this class are the
properties
, which are formed with aDbSet
attached to a specific object.- We define this object using a
DatabaseEntity
model.
- We define this object using a
#
Examples of UseEntityFrameworkCore uses the DatabaseEntity model when accessing the database. In the API team, we typically create an individual file within the Infrastructure namespace for each individual table in the database.
Example DatabaseEntity for the Base API
Schema that we use to create an example table in our database
The class for each DatabaseEntity has a Table attribute, which directly references a specific table present in the schema.
There are also Column attributes for each property, which also directly reference the names of the columns, as well as the data types.
With our model built, we can now call our DatabaseContext object within the Gateway, and access the database using LINQ queries.
For example, in the GetEntityById
method, we call the Database Context, access the DatabaseEntity Property and use the Find
method to match the id in our request with the id column in our database.
The find
method is one of many methods within EntityFrameworkCore.
We can see more methods in use when creating tests which require pre-existing data in the database.
Within our GatewayTests, during the arrange
step shown we create a databaseEntity, then add that entity using the Add
method to track the change to our table, then use the SaveChanges
method to commit that change, as well as any other changes to the database.
#
More InformationFor more information, please visit the online documentation for Entity Framework.