Defining EF Core Models
Learn about the ways to define a model in Entity Framework (EF) Core: using conventions, annotation attributes, and the Fluent API.
EF Core uses a combination of conventions, annotation attributes, and Fluent API statements to build an entity model at runtime so that any actions performed on the classes can be automatically translated into actions performed on the actual database. An entity class represents the structure of a table, and an instance of the class represents a row in that table.
Ways to define a model
First, we will review the three ways to define a model, with code examples, and then we will create some classes that implement those techniques.
Using EF Core conventions to define the model
The code we will write will use the following conventions:
The name of a table is assumed to match the name of a
DbSet
property in theDbContext
class, for example,Products
.The names of the columns are assumed to match the names of properties in the entity model class. For example,
ProductId
.The
string
.NET type is assumed to be anvarchar
type in the database.The
int
.NET type is assumed to be anint
type in the database.The primary key is assumed to be a property that is named
Id
orID
, or when the entity model class is namedProduct
, then the property can be namedProductId
orProductID
. If this property is an integer type or the Guid type, it is also assumed to be anIDENTITY
column(a column type that automatically assigns a value when inserting).
Note: There are many other conventions that we should know, and we can even define our own. We can read more about this from here.
Using EF Core annotation attributes to define the model
Conventions often aren’t enough to map the classes to the database objects completely. Applying annotation attributes is a simple way of adding more smarts to our model. Some common attributes are shown in the following table:
Get hands-on with 1400+ tech skills courses.