我正在尝试在EF Core中动态地映射实体。因此,我不是在dbcontext中明确指定多个关系,而是试图使用反射完成。到目前为止,我的代码如下:
var props = modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.IsForeignKey());
foreach (var prop in props)
{
var name = prop.Name.Split(new[] { "Id" }, StringSplitOptions.None)[0];
var parentTableType = prop.DeclaringEntityType.ClrType
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.Where(f => f.FieldType != typeof(long))
.First(f => f.Name.Contains(name))
.FieldType;
var childTableType = prop.DeclaringEntityType.ClrType
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.Where(f => f.FieldType == typeof(long))
.First(f => f.Name.Contains("Id"))
.DeclaringType;
}
所以这正如我所预期的那样工作,我正在获得每个表的Type
。现在问题是当我尝试实际创建关系时出现问题。两个表的Type
显然是变量,因此我不能像下面一样使用它们作为显式的Type
:
modelBuilder.Entity<parentTableType>()
.HasMany<childTableType>();
有没有办法在运行时将变量转换为具体类型,以允许上述情况发生,或者我试图做这件事是在浪费时间?