![](/img/trans.png)
[英]How to filter Bulk register IEntityTypeConfiguration<> by DbContext
[英]Bulk register IEntityTypeConfiguration<> entity framework core
好的,所以我正在使用带有 dot net core 和 code first migrations 的实体框架。 这本身不是问题,我只是想知道是否有人遇到过更好的方法。
目前我有很多像这样的实体类型配置
public class ExampleEntityConfiguration : IEntityTypeConfiguration<ExampleEntity>
{
public void Configure(EntityTypeBuilder<ExampleEntity> builder)
{
builder.Property(p => p.Id).ValueGeneratedNever();
// more options here
}
}
我像这样在我的 dbcontext 中注册它们
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new ExampleEntityConfiguration());
// lot's more configurations here
}
有没有人遇到或知道注册所有IEntityTypeConfiguration
接口的方法?
看起来很多重复的代码可以通过获取配置列表、循环它们并在上下文中应用来解决。 我只是不知道从哪里开始获取存在于特定命名空间中的IEntityTypeConfiguration
类的列表。
任何帮助/建议都会很棒。
使用 EF Core 2.2+,它变得更加简单:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Assembly assemblyWithConfigurations = GetType().Assembly; //get whatever assembly you want
modelBuilder.ApplyConfigurationsFromAssembly(assemblyWithConfigurations);
}
它可以通过这样的反射来完成:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// get ApplyConfiguration method with reflection
var applyGenericMethod = typeof(ModelBuilder).GetMethod("ApplyConfiguration", BindingFlags.Instance | BindingFlags.Public);
// replace GetExecutingAssembly with assembly where your configurations are if necessary
foreach (var type in Assembly.GetExecutingAssembly().GetTypes()
.Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters))
{
// use type.Namespace to filter by namespace if necessary
foreach (var iface in type.GetInterfaces()) {
// if type implements interface IEntityTypeConfiguration<SomeEntity>
if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)) {
// make concrete ApplyConfiguration<SomeEntity> method
var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
// and invoke that with fresh instance of your configuration type
applyConcreteMethod.Invoke(modelBuilder, new object[] {Activator.CreateInstance(type)});
break;
}
}
}
}
@Evk kan 的好作品被进一步封装在一个可重用的扩展方法中:
public static class ModelBuilderExtensions
{
public static void ApplyAllConfigurationsFromCurrentAssembly(this ModelBuilder modelBuilder, Assembly assembly, string configNamespace = "")
{
var applyGenericMethods = typeof(ModelBuilder).GetMethods( BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
var applyGenericApplyConfigurationMethods = applyGenericMethods.Where(m => m.IsGenericMethod && m.Name.Equals("ApplyConfiguration", StringComparison.OrdinalIgnoreCase));
var applyGenericMethod = applyGenericApplyConfigurationMethods.Where(m=>m.GetParameters().FirstOrDefault().ParameterType.Name== "IEntityTypeConfiguration`1").FirstOrDefault();
var applicableTypes = assembly
.GetTypes()
.Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters);
if (!string.IsNullOrEmpty(configNamespace))
{
applicableTypes = applicableTypes.Where(c => c.Namespace == configNamespace);
}
foreach (var type in applicableTypes)
{
foreach (var iface in type.GetInterfaces())
{
// if type implements interface IEntityTypeConfiguration<SomeEntity>
if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))
{
// make concrete ApplyConfiguration<SomeEntity> method
var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
// and invoke that with fresh instance of your configuration type
applyConcreteMethod.Invoke(modelBuilder, new object[] { Activator.CreateInstance(type) });
Console.WriteLine("applied model " + type.Name);
break;
}
}
}
}
}
并且可以这样调用:
public class ApiDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyAllConfigurationsFromCurrentAssembly("MyRoot.Api.Entities.Configuration");
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
}
@Evk 的回答有点过时,不再有效,@paul vanbladl 的回答是有效的,虽然它包含硬编码的字符串,但我非常讨厌。 如果有人分享我的感觉,我想以创建静态扩展方法的形式提出我的解决方案:
public static ModelBuilder ApplyAllConfigurationsFromAssembly(
this ModelBuilder modelBuilder, Assembly assembly)
{
var applyGenericMethod = typeof(ModelBuilder)
.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.Single(m => m.Name == nameof(ModelBuilder.ApplyConfiguration)
&& m.GetParameters().Count() == 1
&& m.GetParameters().Single().ParameterType.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>));
foreach (var type in assembly.GetTypes()
.Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters))
{
foreach (var iface in type.GetInterfaces())
{
if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))
{
var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
applyConcreteMethod.Invoke(modelBuilder, new object[] {Activator.CreateInstance(type)});
break;
}
}
}
}
并且,如果您的配置类与您的 DbContext 存储在同一个程序集中,您可以按如下方式使用此方法:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyAllConfigurationsFromAssembly(GetType().Assembly);
base.OnModelCreating(modelBuilder);
}
-- 数据库上下文
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
base.OnModelCreating(builder);
}
我真的很喜欢@paul vanbladel 为将代码移动到扩展方法而提供的答案。 我还需要从其他程序集中调用它,因此我创建了一个枚举并将适用的类型更改为不同的设置。
IEnumerable<Type> assemblyTypeList;
switch (pAssemblyMethodType)
{
case AssemblyMethodType.CallingAssembly:
assemblyTypeList = Assembly.GetCallingAssembly()
.GetTypes()
.Where(c => c.IsClass
&& !c.IsAbstract
&& !c.ContainsGenericParameters);
break;
case AssemblyMethodType.ExecutingAssembly:
assemblyTypeList = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(c => c.IsClass
&& !c.IsAbstract
&& !c.ContainsGenericParameters);
break;
default:
throw new ArgumentOutOfRangeException(nameof(pAssemblyMethodType), pAssemblyMethodType, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.