Configuring the model mapping

EF Core uses conventions to map your entities into database objects, but you can also configure the mapping explicitly in two ways:

  • Data Annotations: Defines each type and property map to the database by using attributes
  • Fluent API: The model is defined by overriding the DbContext OnModelCreating method and using a ModelBuilder class to define the mapping

In this book, we'll mainly use the EF Core conventions, but when there's a need to fine-tune the mapping, it will be done with the Fluent API.

Here are the default EF Core conventions that are used by our model:

  • Table names take the plural form of the entity name. For example, Products is the table name for the Product entity.
  • Column names are the same as the property name.
  • Primary keys are named in the format of [EntityName]Id, for example, ProductId.
  • Properties that reference an entity, or a collection of entities, create a relationship between the entities in the form of foreign key constraints.

This list covers almost everything you'd need to create a model, however, there are times where you'll need make adjustments. For example, in the GiveNTake application, a category can be a parent category, or a subcategory of another parent category. This means that there are two relationships between the category entity and itself:

public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Category> Subcategories { get; set; }
public Category ParentCategory { get; set; }
}

EF Core is not able to understand what the relationships mean and if they are required or not. To help it, we'll define the relationships explicitly in the DbContext.OnModelCreating() method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>()
.HasOne(sub => sub.ParentCategory)
.WithMany(c => c.Subcategories)
.IsRequired(false);

modelBuilder.Entity<Product>()
.HasOne(p => p.Category)
.WithMany()
.IsRequired();

...
}

The ModelBuilder class is the access point for the EF Core Fluent API. The Fluent API gives you an API for shaping the entities, relationships, constraints, and conventions of your model. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.172.115