Skip to content

Instantly share code, notes, and snippets.

@ducmeit1
Created July 10, 2019 07:07
Show Gist options
  • Save ducmeit1/04cd34ef3a3d1b87259212df05649cde to your computer and use it in GitHub Desktop.
Save ducmeit1/04cd34ef3a3d1b87259212df05649cde to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
namespace Demo {
public static class Extensions
{
/// <summary>
/// Auto find and apply all IEntityTypeConfiguration to modelBuilder
/// </summary>
public static void ApplyAllConfigurations<TDbContext>(this ModelBuilder modelBuilder)
where TDbContext : DbContext
{
var applyConfigurationMethodInfo = modelBuilder
.GetType()
.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.First(m => m.Name.Equals("ApplyConfiguration", StringComparison.OrdinalIgnoreCase));
var ret = typeof(TDbContext).Assembly
.GetTypes()
.Select(t => (t,
i: t.GetInterfaces().FirstOrDefault(i =>
i.Name.Equals(typeof(IEntityTypeConfiguration<>).Name, StringComparison.Ordinal))))
.Where(it => it.i != null)
.Select(it => (et: it.i.GetGenericArguments()[0], cfgObj: Activator.CreateInstance(it.t)))
.Select(it =>
applyConfigurationMethodInfo.MakeGenericMethod(it.et).Invoke(modelBuilder, new[] {it.cfgObj}))
.ToList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment