這是我的問題,我想將我所有的流利的 api 配置類作為一個串列。然后將它們應用到我的 DbContext 中。我的域類都像這樣繼承 BaseModel ;
public class Role : BaseModel
{
public string RoleTitle { get; set; }
public string RoleDescription { get; set; }
public ICollection<UserRole> UserRoles { get; set; }
}
和這樣的配置:
public class RoleConfig : IEntityTypeConfiguration<Role>
{
public void Configure(EntityTypeBuilder<Role> builder)
{
builder.Property(r => r.RoleTitle)
.IsRequired()
.HasMaxLength(100);
builder.Property(r => r.RoleDescription)
.HasMaxLength(250);
}
}
我已經在我的 DbContext 中使用的是:
modelBuilder.ApplyConfiguration(new UserConfig());
modelBuilder.ApplyConfiguration(new RoleConfig());
modelBuilder.ApplyConfiguration(new UserRoleConfig());
and more .....
我正在尋找的是:
foreach (var config in ConfigClasses)
{
modelBuilder.ApplyConfiguration(config);
}
所以問題是我怎樣才能得到所有的配置類?我試過這個但不作業:
var type = typeof(IEntityTypeConfiguration<Anytype : BaseModel>);
var ConfigClasses= AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p)).ToList();
問題是IEntityTypeConfiguration<Anytype : BaseModel>任何 idia 我該怎么做?以這種方式或任何其他方式?
uj5u.com熱心網友回復:
有一種ModelBuilder添加所有配置的方法,您可以使用它:
modelBuilder.ApplyConfigurationsFromAssembly(typeof(YourDbContext).Assembly);
正如您所知道的那樣YourDbContext,配置必須在同一個程式集中。
uj5u.com熱心網友回復:
下面是一個關于如何通過反射找到泛型介面的示例:
var appDomain = AppDomain.CurrentDomain;
var assemblies = appDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var types = assembly.GetTypes();
foreach (var type in types)
{
var interfaces = type.GetInterfaces();
foreach (var iface in interfaces)
{
if (iface.IsGenericType)
{
var genericInterface = iface.GetGenericTypeDefinition();
if(genericInterface == typeof(MyGenericInterface<>))
{
Console.WriteLine($"Type {type.Name} implements {genericInterface.Name}");
}
}
}
}
}
使用此草圖,您應該能夠找到所有需要的型別,通過初始化它們Activator.CreateInstance()并將這些實體應用于您的模型構建器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435747.html
