如何在实体框架的POCO中为这种关系建模?

时间:2018-07-09 15:58:58

标签: c# entity-framework entity-framework-6

我的问题是关于以下所示的架构。我有一个Tenant,其中有InboundSources,而其中又有InboundSourceActions。我无法进行任何更改,因为它属于依赖于此确切模式的第三方产品。

Schema

我有以下课程(Tenant无关紧要,但其中包含的内容是为了说明如何设置导航属性/确保其按我的意愿工作):

[Table("tenants")]
public class Tenant
{
    [Key]
    public int Id { get; set; }

    [Column("tenant")]
    [StringLength(64)]
    public string Name { get; set; }

    // ...blah blah

    // Navigation property
    public virtual ICollection<InboundSource> InboundSources { get; set; }
}

[Table("inbound_source")]
public class InboundSource
{
    [Key]
    public int Id { get; set; }

    // Navigation properties back to Tenant
    public int TenantId { get; set; }
    public virtual Tenant Tenant { get; set; }

    [StringLength(255)]
    public string Description { get; set; }

    // ...blah blah

    // Navigation property
    public virtual ICollection<InboundSourceAction> InboundSourceActions { get; set; }
}

[Table("inbound_source_actions")]
public class InboundSourceAction
{
    [Key]
    public int Id { get; set; }

    // Navigation property back to InboundSource
    [StringLength(255)]
    public string Extension { get; set; }
    public virtual InboundSource InboundSource { get; set; }

    [StringLength(255)]
    public string Action { get; set; }

    // ...blah blah
}

我无法在InboundSourceInboundSourceActions之间实现导航属性。在上面的模式中,该关系以红色显示,但实际上未在数据库中作为外键或其他任何形式显示。我正在寻找如何在InboundSourceInboundSourceAction类中对红色关系进行建模。我一直在尝试添加ForeignKey属性,但无法使其正常工作:

[Table("inbound_source")]
public class InboundSource
{
    [Key]
    public int Id { get; set; }

    // Blah blah

    [ForeignKey("Extension")]
    public virtual ICollection<InboundSourceAction> InboundSourceActions { get; set; }
}

[Table("inbound_source_actions")]
public class InboundSourceAction
{
    [Key]
    public int Id { get; set; }

    [StringLength(255)]
    [ForeignKey("InboundSource")]
    public string Extension { get; set; }
    public virtual InboundSource InboundSource { get; set; }

    // Blah blah
}

但这会导致异常:'InboundSourceAction_InboundSource_Target_InboundSourceAction_InboundSource_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'Extension' on entity 'InboundSourceAction' does not match the type of property 'Id' on entity 'InboundSource' in the referential constraint 'InboundSourceAction_InboundSource'. '

所以我的问题是:EF完全支持这种情况吗?如果支持,怎么做?

1 个答案:

答案 0 :(得分:0)

在EF6中,实体具有单个密钥,并且任何外键都必须引用实体密钥。但是EF不在乎您将哪个键声明为实体键。如果将inbound_source作为(ID)和(Extension)这两个键,则可以将其中一个声明为实体键。