gpt4 book ai didi

c# - 类型上的 EF 核心实体

转载 作者:行者123 更新时间:2023-11-30 16:38:41 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

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

关于c# - 类型上的 EF 核心实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54664926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com