Entity Framework Core Model Configuration and Mapping
Introduction
This article is for Entity Framework Core model configuration. By using this technique we can easily maintain the code and apply changes quickly.
Let's demonstrate how we can use assembly to dynamically initialize the generic classes.
Used Technologies
- Entity Framework Core
- Assembly (System.Reflection)
Step 1
Create a class with following properties:
public class Person
{
public int Id { get; set; }
public string Name{ get; set; }
public string Gender { get; set; }
public int Age { get; set; }
}
Step2
Create entity configuration abstract base class
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace EntityConfigurationBase
{
public abstract partial class EntityCongurationMapper<T> : IEntityTypeConfiguration<T> where T : class
{
public abstract void Configure(EntityTypeBuilder<T> builder);
}
}
***Inherit entity configuration abstract base class
using DotnetCoreSamples.Domain.EntityModel.Blogs;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace EntityConfigurationBase
{
public partial class PersonEntityConfiguration:EntityCongurationMapper<Person>
{
public override void Configure(EntityTypeBuilder<Person> builder)
{
builder.HasKey(m => m.Id);
builder.Property(m => m.Name).HasMaxLength(250);
builder.Property(m => m.Gender ).HasMaxLength(20);
}
}
}
Step3
Create a context class and override OnModelCreating(ModelBuilder modelBuilder) method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using DotnetCoreSamples.Domain.EntityModel.Blogs;
using System.Reflection;
using DotnetCoreSamples.Data.Mapping;
using Microsoft.Extensions.Configuration;
using System.Configuration;
namespace EntityConfigurationBase
{
public class MyCustomContext : DbContext
{
public MyCustomContext()
{
}
public MyCustomContext(DbContextOptions options) : base(options)
{
//Database.EnsureCreated();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null && type.BaseType.IsGenericType &&
type.BaseType.GetGenericTypeDefinition() == typeof(EntityConfigurationBase<>));
foreach (var type in typesToRegister)
{
dynamic configInstance = Activator.CreateInstance(type);
modelBuilder.ApplyConfiguration(configInstance);
}
}
}
}