Saturday, 4 May 2024

Entity Framework Core - 3 ways to configure/customize entity models in EF Core

 Models can be customized in the entity framework by 3 ways:

  • Conventions
  • DataAnnotations
  • FluentAPI/OnModelCreating

Entity framework by default uses some conventions like, if a model has property with name 'Id' or ClassNameId (i.e. CustomerID) it will set this property as primary key, second way to customize model using 'Data Annotation' (attributes on properties) and third way to customize model on 'OnModelCreating()' event handler/fluent API.

Fluent API configuration has the highest precedence and will override conventions and data annotations.

 Below example show how to configure model on 'OnModelCreating'

internal class MyContext : DbContext {

    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {        

            modelBuilder.Entity<Blog>()

            .Property(b => b.Url)

            .IsRequired();

    }

}

Grouping Configuration

Sometimes it's possible that Size of OnModelCreating method is too large, to reduce the size of the OnModelCreating method, all configuration for an entity type can be extracted to a separate class implementing IEntityTypeConfiguration<TEntity>.

We can create a class implementing IEntityTypeConfiguration interface and provide definition to Configure() method. same thing what we were doing on 'OnModelCreating' we will do on Configure() method but it's specific for particular model/entity.

after implementing interface, we need to call Configure method on 'OnModelCreating method'

public class BlogEntityTypeConfiguration : IEntityTypeConfiguration<Blog> {

        public void Configure(EntityTypeBuilder<Blog> builder) {

        builder

            .Property(b => b.Url)

            .IsRequired();

    }

}

Calling Configure method in OnModelCreating:

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

Using EntityTypeConfigurationAttribute

Instead calling Configure method for each entity, we can apply EntityTypeConfigurationAttribure on Entity i.e.

[EntityTypeConfiguration(typeof(BookConfiguration))]

public class Book{

    public int Id { get; set; }

    public string Title { get; set; }

    public string Isbn { get; set; }

}

Adding/Removing Convention

You can find default conventions provided by EFCore in the list of classes that implement IConvention interface, you can add your own convention or remove any default convention like:

protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) {

    configurationBuilder.Conventions.Remove(typeof(ForeignKeyIndexConvention));

}

No comments:

Post a Comment

How to create and use middleware in asp.net core

Middleware is piece of code that's assembled into an app pipeline to handle requests and responses.  Each middleware component in the re...