类型上的EF核心实体

问题描述 投票:3回答:1

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

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

c# entity-framework-core
1个回答
2
投票

有许多Fluent API非泛型方法重载接受string类型名称或Type类型参数。

既然你有Type变量,你可以使用相应的EntityHasMany重载:

modelBuilder.Entity(parentTableType)
    .HasMany(childTableType);  
© www.soinside.com 2019 - 2024. All rights reserved.