实体框架6:两个不相关的实体映射到同一张表

时间:2018-12-04 09:16:18

标签: c# entity-framework-6

我想将一个表映射到两个不相关的实体:EntityBasic和EntityAdvanced。 EntityAdvanced具有此功能不需要的其他业务逻辑,我想创建一个仅具有表中字段的新Entity。

MyTable:

MyTableId : Guid
ParentId : Guid
Name : string
Description : string
Type : int

EntityBasic:

[Table("MyTable")]
public class EntityBasic
{
    [Key]
    public Guid MyTableId { get; set; }

    public Guid ParentId { get; set }

    public string Name { get; set; }

    public string Description { get; set; }

    public int Type { get; set; }

    [ForeignKey("ParentId")]
    public virtual List<EntityBasic> Entities{ get; set; }
}

EntityAdvanced:

[Table("MyTable")]
public class EntityAdvanced
{
    private List<EntityAdvanced> _entities;
    private List<Filter> _filters;

    [Key]
    public Guid MyTableId { get; set; }

    public Guid ParentId { get; set }

    public string Name { get; set; }

    public string Description { get; set; }

    public int Type { get; set; }

    [ForeignKey("ParentId")]
    public virtual List<EntityAdvanced> Entities
    {
        get { //Some complicated getter }
        set { //Some complicated setter }
    }

    [NotMapped]
    public string ImageUrl
    {
        get { //Some complicated getter }
        set { //Some complicated setter }
    }

    public void SetFilters(//Some parameters)
    {
        //Some logic 
    }
}

执行此操作时出现此错误:

  

实体类型'EntityAdvanced'和'EntityBasic'无法共享表'MyTable',因为它们不在同一类型层次结构中,或者没有有效的一对一外键关系且它们之间具有匹配的主键。

有没有办法做我想做的事?

2 个答案:

答案 0 :(得分:1)

作为基础开始,您的EntityAdvanced应该继承EntityBasic,因为它们共享相同的基础属性集。您无需重写它们。请注意extends EntityBasic

[Table("MyTable")]
public class EntityBasic
{
    [Key]
    public Guid MyTableId { get; set; }

    public Guid ParentId { get; set }

    public string Name { get; set; }

    public string Description { get; set; }

    public int Type { get; set; }

    [ForeignKey("ParentId")]
    public virtual List<EntityBasic> Entities{ get; set; }
}

[NotMapped]
public class EntityAdvanced : EntityBasic
{    
    //[NotMapped]
    public string ImageUrl
    {
        get { //Some complicated getter }
        set { //Some complicated setter }
    }

    public void SetFilters(//Some parameters)
    {
        //Some logic 
    }
}

List<EntityBasic> Entities使用继承,可以引用EntityAdvanced对象,因此您不再需要声明:

[ForeignKey("ParentId")]
public virtual List<EntityAdvanced> Entities
{
    get { //Some complicated getter }
    set { //Some complicated setter }
}

您可以获得有关使用实体框架here实现继承的有用信息。

编码愉快!

答案 1 :(得分:0)

我认为您可以使用Entity Framework 6的“表格拆分”功能 在这里看看示例:https://www.c-sharpcorner.com/UploadFile/ff2f08/table-splitting-in-entity-framework-6-code-first-approach/