实体框架中的自定义关系

时间:2017-01-27 18:48:19

标签: c# entity-framework

我有以下三个表(只是一个例子)

public class User
{
    public int id { get; set; }
    public string name { get; set; }
    public List<Code> Codes { get; set; }
}

public class Device
{
    public int id { get; set; }
    public string name { get; set; }
    public List<Code> Codes { get; set; }
}

public class Code
{
    public int id { get; set; }
    public int entity_id { get; set; }
    public string entity_type { get; set; }
    public string code { get; set; }
}

现在代码可以属于用户或设备,这将由entity_type的值(即“用户”或“设备”)确定。如何在实体框架中实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以将您的Code类更改为

public class Code
{
    public int id { get; set; }
    public User user { get; set; }
    public Device device { get; set; }
    public string code { get; set; }
}

这样,其中一个属性可以为null。

希望它有所帮助。

缺点是您可以拥有一个拥有用户和设备的代码