EF Core Type configuration

Entity Framework Core provides a range of options for configuring types (entities) using the Fluent API. These options are available as methods that can be chained to the ModelBuilder.Entity() method, which is available in generic and non-generic versions. The non-generic methods take the name or type of the entity to be configured:

language-csharp
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity(typeof(EntityName))...
}

or

language-csharp
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity("EntityName")...
}

Most often, you will use the generic version to specify the type that the configuration applies to. This option is the one that is used throughout this guide:

language-csharp
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<EntityName>()...
}

Methods available for type configuration are detailed below.

HasAlternateKey Generates a unique constraint for the specified property or properties
HasAnnotation Provides a means to apply annotations via the Fluent API
HasBaseType Specifies the base type of the entity
HasIndex Generates an index on the specified property or properties
HasKey Denotes the specified property as the entity key
HasMany Specifies the Many end of a relationship
HasOne Specifies the One end of a relationship
Ignore |Denotes that the entity should be omitted from mapping
ToTable Specifies the database table that the entity should be mapped to
Property Provides access to property configuration

Date Modified: 2023-02-27
Author:

Edit this page in GitHub

Got any EF Core Question?