EF核心实体类型

时间:2019-02-13 07:42:54

标签: c# entity-framework-core

我正在尝试在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>();

在运行时是否有将变量转换为具体类型的方法,以允许上述情况发生?还是我在浪费时间尝试这样做?

1 个答案:

答案 0 :(得分:2)

接受string类型名称或Type类型参数的Fluent API 非通用方法重载很多。

由于拥有Type变量,因此可以使用相应的EntityHasMany重载:

modelBuilder.Entity(parentTableType)
    .HasMany(childTableType);