好,所以我正在使用具有点网核心和代码优先迁移的实体框架。因此这不是问题,我只是想知道是否有人遇到过更好的方法。
目前,我有许多类似的实体类型配置
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
类的列表。
任何帮助/建议都很好。
可以通过这样的反射来完成:
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;
}
}
}
}
使用EF Core 2.2+,它变得更加简单:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Assembly assemblyWithConfigurations = GetType().Assembly; //get whatever assembly you want
modelBuilder.ApplyConfigurationsFromAssembly(assemblyWithConfigurations);
}
@ Evk的出色著作被进一步封装在可重用的扩展方法中:
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 van bladel的回答是可行的,尽管它包含硬编码的字符串,但我非常讨厌。如果有人有我的感觉,我想以创建静态扩展方法的形式提出我的解决方案:
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);
}
我真的很喜欢为将代码移至扩展方法而提供的答案@paul van bladel。我还需要从其他程序集中调用它,因此我创建了一个枚举并更改了applyTypes来进行不同的设置。
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);
}
-DbContext
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
base.OnModelCreating(builder);
}