0

解决此问题的正确方法是什么:假设我有一个对象表:

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 枚举描述。我想将它们存储在不同的表中,并且在查询我的对象时,我希望我的对象根据其 Id 从 Control 特定表中作为 IControl Control 包含在内。

我知道我可以使用 TPH 继承,但我的控制表会很大,有很多空列,因为控件有很多不同的属性,具体取决于它们的类型。

4

1 回答 1

0

听起来您想IControl根据ControlType和动态查询ControlId.

在不添加验证(空检查等)的情况下,我可以这样做:

//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 可以让你找到你只需要一些额外步骤的对象:

  • Type通过反射找到实际的。
  • 使用DbContext.Find相应的Type并搜索Id.

不太确定您的ControlType实际情况,因此可能需要调整此代码。我只是使用 astring来存储松散链接表的类型。这样我就不必Enum每次添加或删除 POCO 时都进行调整。

于 2020-10-23T19:17:30.513 回答