Creating and Configuring a Model - EF Core (2024)

  • Article

EF Core uses a metadata model to describe how the application's entity types are mapped to the underlying database. This model is built using a set of conventions - heuristics that look for common patterns. The model can then be customized using mapping attributes (also known as data annotations) and/or calls to the ModelBuilder methods (also known as fluent API) in OnModelCreating, both of which will override the configuration performed by conventions.

Most configuration can be applied to a model targeting any data store. Providers may also enable configuration that is specific to a particular data store and they can also ignore configuration that is not supported or not applicable. For documentation on provider-specific configuration see theDatabase providerssection.

Tip

You can view this article's samples on GitHub.

Use fluent API to configure a model

You can override theOnModelCreatingmethod in your derived context and use thefluentAPI to configure your model. This is the most powerful method of configuration and allows configuration to be specified without modifying your entity classes. Fluent API configuration has the highest precedence and will override conventions and data annotations. The configuration is applied in the order the methods are called and if there are any conflicts the latest call will override previously specified configuration.

using Microsoft.EntityFrameworkCore;namespace EFModeling.EntityProperties.FluentAPI.Required;internal class MyContext : DbContext{ public DbSet<Blog> Blogs { get; set; } #region Required protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .Property(b => b.Url) .IsRequired(); } #endregion}public class Blog{ public int BlogId { get; set; } public string Url { get; set; }}

Grouping configuration

To reduce the size of the OnModelCreating method all configuration for an entity type can be extracted to a separate class implementing IEntityTypeConfiguration<TEntity>.

public class BlogEntityTypeConfiguration : IEntityTypeConfiguration<Blog>{ public void Configure(EntityTypeBuilder<Blog> builder) { builder .Property(b => b.Url) .IsRequired(); }}

Then just invoke the Configure method from OnModelCreating.

new BlogEntityTypeConfiguration().Configure(modelBuilder.Entity<Blog>());

Applying all configurations in an assembly

It is possible to apply all configuration specified in types implementing IEntityTypeConfiguration in a given assembly.

modelBuilder.ApplyConfigurationsFromAssembly(typeof(BlogEntityTypeConfiguration).Assembly);

Note

The order in which the configurations will be applied is undefined, therefore this method should only be used when the order doesn't matter.

Using EntityTypeConfigurationAttribute on entity types

Rather than explicitly calling Configure, an EntityTypeConfigurationAttribute can instead be placed on the entity type such that EF Core can find and use appropriate configuration. For example:

[EntityTypeConfiguration(typeof(BookConfiguration))]public class Book{ public int Id { get; set; } public string Title { get; set; } public string Isbn { get; set; }}

This attribute means that EF Core will use the specified IEntityTypeConfiguration implementation whenever the Book entity type is included in a model. The entity type is included in a model using one of the normal mechanisms. For example, by creating a DbSet<TEntity> property for the entity type:

public class BooksContext : DbContext{ public DbSet<Book> Books { get; set; } //...

Or by registering it in OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder){ modelBuilder.Entity<Book>();}

Note

EntityTypeConfigurationAttribute types will not be automatically discovered in an assembly. Entity types must be added to the model before the attribute will be discovered on that entity type.

Use data annotations to configure a model

You can also apply certain attributes (known as Data Annotations) to your classes and properties. Data annotations will override conventions, but will be overridden by Fluent API configuration.

using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using Microsoft.EntityFrameworkCore;namespace EFModeling.EntityProperties.DataAnnotations.Annotations;internal class MyContext : DbContext{ public DbSet<Blog> Blogs { get; set; }}[Table("Blogs")]public class Blog{ public int BlogId { get; set; } [Required] public string Url { get; set; }}

Built-in conventions

EF Core includes many model building conventions that are enabled by default. You can find all of them in the list of classes that implement the IConvention interface. However, that list doesn't include conventions introduced by third-party database providers and plugins.

Applications can remove or replace any of these conventions, as well as add new custom conventions that apply configuration for patterns that are not recognized by EF out of the box.

Tip

The code shown below comes from ModelBuildingConventionsSample.cs.

Removing an existing convention

Sometimes one of the built-in conventions may not appropriate for your application, in which case it can be removed.

Tip

If your model doesn't use mapping attributes (aka data annotations) for configuration, then all conventions with the name ending in AttributeConvention can be safely removed to speed up model building.

Example: Don't create indexes for foreign key columns

It usually makes sense to create indexes for foreign key (FK) columns, and hence there is a built-in convention for this: ForeignKeyIndexConvention. Looking at the model debug view for a Post entity type with relationships to Blog and Author, we can see two indexes are created--one for the BlogId FK, and the other for the AuthorId FK.

 EntityType: Post Properties: Id (int) Required PK AfterSave:Throw ValueGenerated.OnAdd AuthorId (no field, int?) Shadow FK Index BlogId (no field, int) Shadow Required FK Index Navigations: Author (Author) ToPrincipal Author Inverse: Posts Blog (Blog) ToPrincipal Blog Inverse: Posts Keys: Id PK Foreign keys: Post {'AuthorId'} -> Author {'Id'} ToDependent: Posts ToPrincipal: Author ClientSetNull Post {'BlogId'} -> Blog {'Id'} ToDependent: Posts ToPrincipal: Blog Cascade Indexes: AuthorId BlogId

However, indexes have overhead, and it may not always be appropriate to create them for all FK columns. To achieve this, the ForeignKeyIndexConvention can be removed when building the model:

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder){ configurationBuilder.Conventions.Remove(typeof(ForeignKeyIndexConvention));}

Looking at the debug view of the model for Post now, we see that the indexes on FKs have not been created:

 EntityType: Post Properties: Id (int) Required PK AfterSave:Throw ValueGenerated.OnAdd AuthorId (no field, int?) Shadow FK BlogId (no field, int) Shadow Required FK Navigations: Author (Author) ToPrincipal Author Inverse: Posts Blog (Blog) ToPrincipal Blog Inverse: Posts Keys: Id PK Foreign keys: Post {'AuthorId'} -> Author {'Id'} ToDependent: Posts ToPrincipal: Author ClientSetNull Post {'BlogId'} -> Blog {'Id'} ToDependent: Posts ToPrincipal: Blog Cascade

When desired, indexes can still be explicitly created for foreign key columns, either using the IndexAttribute or with configuration in OnModelCreating.

Debug view

The model builder debug view can be accessed in the debugger of your IDE. For example, with Visual Studio:

Creating and Configuring a Model - EF Core (1)

It can also be accessed directly from code, for example to send the debug view to the console:

Console.WriteLine(context.Model.ToDebugString());

The debug view has a short form and a long form. The long form also includes all the annotations, which could be useful if you need to view relational or provider-specific metadata. The long view can be accessed from code as well:

Console.WriteLine(context.Model.ToDebugString(MetadataDebugStringOptions.LongDefault));
Creating and Configuring a Model - EF Core (2024)

FAQs

How to create a model in Entity Framework core? ›

You use the DbContext Scaffold command to generate the model. The command has two required arguments - a connection string and a provider. The connection string will depend on your environment and database provider. The provider argument is the Entity Framework provider for your chosen database.

What is the difference between OnModelCreating and OnConfiguring? ›

The OnConfiguring() method allows us to select and configure the data source to be used with a context using DbContextOptionsBuilder. In our upcoming article, we will discuss more about this method. The OnModelCreating() method allows us to configure the model using ModelBuilder Fluent API.

How to configure Entity Framework in C#? ›

A Step-by-Step Guide to Configuring Entity Framework in Your . NET Web API Project
  1. 1 – Install NuGet Packages. ...
  2. 2 – Create an Empty Database. ...
  3. 3 – Adding DbContext class. ...
  4. 4 – SQL Database Configuration. ...
  5. 5 – Migrations. ...
  6. 6 – Database Update. ...
  7. 7 – Scaffold API Controller.
Jan 16, 2023

How to set up Entity Framework Core to a project? ›

Introduction
  1. Step 1: Create a New . NET Core Project. ...
  2. Step 2: Install Entity Framework Core. ...
  3. Step 3: Create a Class. ...
  4. Step 4: Create the DbContext. ...
  5. Step 5: Configure the Database connection. ...
  6. Step 6: Create a migration. ...
  7. Step 7: Implement Entity Framework in Your Application.
Oct 20, 2023

What is the EF core model of an entity? ›

EF Core Model

The model includes data and can also include behavior. Typically, models for CRUD applications don't tend to incorporate a lot of behavior. Models are expressed as a collection of classes written in C#. Each class represents an entity (a.k.a. business object, domain object) within the application domain.

What is model first approach in Entity Framework Core? ›

Model-first approach supposes creating entity model (its conceptual part), and then generating context and entity cases and DDL for creating a database schema, based on the the model. For example, it was implemented in that way in EDM Designer in Visual Studio 2010 and later.

Why do we use OnModelCreating? ›

The OnModelCreating method is overridden to configure the mapping between the model classes and the database schema. This method is used to define the tables, columns, relationships, and constraints in the database schema. In the OnModelCreating method, the ModelBuilder class is used to configure the entity types.

When OnModelCreating is called EF Core? ›

The OnModelCreating method is typically called when you create the first instance of a derived context or use data access in your application. The reason this is at different points in your applications is probably due to the fact that you call your data access layers in different points in the lifecycle.

What are DbContextOptions? ›

DbContextOptions() This is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs.

What are the disadvantages of an Entity Framework? ›

What are the disadvantages of Entity Framework? Ans: There are certain disadvantages to Entity Framework, including as performance overhead because of its abstraction layer, the potential for created SQL inefficiencies, a lack of control over complex queries, and a learning curve for advanced functionality.

What is the difference between Entity Framework and Entity Framework Core? ›

Entity Framework (EF) refers to the older versions designed for the . NET Framework. Entity Framework Core (EF Core) is the modern, cross-platform ORM specifically designed for . NET Core and later versions.

What is fluent API in EF Core? ›

EF Core's Fluent API provides methods for configuring various aspects of your model: Model-wide configuration. Type configuration. Property configuration.

How to create a model Entity Framework? ›

In Model First, you define your model in an Entity Framework designer then generate SQL, which will create database schema to match your model and then you execute the SQL to create the schema in your database. The classes that you interact with in your application are automatically generated from the EDMX file.

Which approach can be used in EF Core to create entity data model? ›

Now, to model your entities, there are three approaches in EF Core. These include: Code First, Model First and Database First. When following the Code First approach you would typically create the entity classes initially.

How to create a new model in C#? ›

cs".
  1. In the Solution Explorer.
  2. Right-click on the "Model" folder then select "Add" -> "Class".
  3. In the Template Window, select "Installed template" -> "Visual C#" -> "Class".
  4. Click on the "OK" button.
Jun 22, 2022

How to create a model in asp net core MVC? ›

Adding a Model Class

In the MVC application in Visual Studio, and right-click on the Model folder, select Add -> and click on Class... It will open the Add New Item dialog box. In the Add New Item dialog box, enter the class name Student and click Add. This will add a new Student class in model folder.

Top Articles
Latest Posts
Article information

Author: Moshe Kshlerin

Last Updated:

Views: 6438

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Moshe Kshlerin

Birthday: 1994-01-25

Address: Suite 609 315 Lupita Unions, Ronnieburgh, MI 62697

Phone: +2424755286529

Job: District Education Designer

Hobby: Yoga, Gunsmithing, Singing, 3D printing, Nordic skating, Soapmaking, Juggling

Introduction: My name is Moshe Kshlerin, I am a gleaming, attractive, outstanding, pleasant, delightful, outstanding, famous person who loves writing and wants to share my knowledge and understanding with you.