.net 根据其类型EF core获取相关对象
解决这个问题的正确方法是什么: 假设我有一个对象表:.net 根据其类型EF core获取相关对象,.net,.net-core,entity-framework-core,.net,.net Core,Entity Framework Core,解决这个问题的正确方法是什么: 假设我有一个对象表: public class Object { public Guid Id { get; set; } public ControlType Type { get; set; } public Guid ControlId { get; set; } public IControl Control { get; set; } } IControl是由10个不同的控件对象实现的接口。它们的类型由ControlType enum描述。我希望将它们
public class Object
{
public Guid Id { get; set; }
public ControlType Type { get; set; }
public Guid ControlId { get; set; }
public IControl Control { get; set; }
}
IControl是由10个不同的控件对象实现的接口。它们的类型由ControlType enum描述。我希望将它们存储在不同的表中,在查询我的对象时,我希望我的对象作为IControl控件包含在控件特定的表中,具体取决于它的Id
我知道我可以使用TPH继承,但我的控件表将非常庞大,有许多空列,因为控件根据其类型有许多不同的属性。听起来您想根据
控件类型和控件ID
动态查询IControl
在不添加验证(空检查等)的情况下,我可以使用以下方法:
//assuming the names of your ControlType Enums exactly match the string name of their actual Type.
//assume your Object is as follows
// var obj = new Object() {id = a8, Type = Ctrl8, ControlId = e3}
//context is the DbContext of EF.
//need to reflect on the EF Context and find the correct type
var controlType = context.Model.FindEntityType(Enum.GetName(typeof(ControlType), obj.Type)))?.ClrType;
//search the context for the Control
var myCtrl = context.Find(controlType , obj.ControlId)
如果您想要松散的关系(无FK约束),EF可以让您找到您只需要一些额外步骤的对象:
- 通过反射查找实际的
类型
- 使用
DbContext。查找带有相应类型的并搜索Id
不太确定您的控件类型实际上是什么,因此此代码可能需要调整。我只是使用字符串来存储松散链接表的类型。这样,我就不必每次添加或删除POCO时都调整Enum