The way Entity Framework generates a database schema can seem like magic, but in fact there are rules. Absent guidance in the form of data annotations or the Fluent API (both of which we’ll discuss later in this chapter), it will use the following conventions:
• Any class that is represented in the context by a DbSet<T>
will become a table.
• Any class that is referenced by a class represented as a DbSet<T>
will become a table.
• Entity Framework will pluralize the class names using its pluralization service.
• A property named “Id
” or “<ClassName>Id
” will be inferred as the primary key.
• The properties of a class will become fields in the corresponding table.
• If the primary key property is an integer, it will be a database-generated identity field.
• If a property is a string, it will be made nullable and assigned the maximum length supported by the server (nvarchar(MAX)
in SQL).
• If a property is a Boolean, it will be made a not nullable bit.
• Foreign keys will be inferred as required (but Microsoft recommends that they be explicitly included).
• If a property representing a foreign key is not nullable, a cascade delete will be established in the database.
• If a class is to be included in a database (because it is referenced by a DbSet
or by another class referenced by a DbSet
), but it does not have a field that can be inferred as a primary key, that class will be interpreted as a complex type.
• Complex types will be represented in the database as fields in the table that references them.
• The fields that represent complex types will be named Type_Field
.
Put On Your Thinking Hat
I don’t know about you, but I have a hard time remembering lists of rules like that one. Well, the good news is that you don’t have to memorize it (you can always just build the database and see if you get what you want), but here’s a little exercise to help you get the basics down.
Given the class model shown here, can you predict the database schema the Entity Framework will produce?
How many tables will the schema contain, assuming the context references the Customers
class?
What will their names be?
How will the Address
class be represented?
What will the field type of the Customers.FirstName
property be?
What will the field that stores the Zipcode
be named?
Put On Your Thinking Hat
How’d you do?
How many tables will the schema contain, assuming the context references the Customers
class?
Two. The Address
class doesn’t contain a primary key, so it will be treated as a complex type.
What will their names be?
Customers
and Orders
.
How will the Address
class be represented?
The properties of the Address
class will be included in the Customer
table.
What will the field type of the Customers.FirstName
property be?
It’s a String
, so it will be represented in SQL as nvarchar(MAX)
.
What will the field that stores the Zipcode
be named?
Their names will be prefaced with “Address_”. For example, the City
property will become Address_City
.