Created
July 10, 2019 07:07
-
-
Save ducmeit1/04cd34ef3a3d1b87259212df05649cde to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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