使用主表键以代码优先的方式链接到不同的表作为外键

时间:2017-11-07 08:33:07

标签: c# entity-framework ef-code-first code-first master-detail

我使用代码优先使用MVC5的问题。这是我的情景:

Simple Model

我有LeaveApplication标头表,其中包含CompanyCode和WorkGroup字段。而且,还有一个详细信息表LeaveApplicationDetails,其中包含LeaveTypeCode。现在,LeaveTypes在另一个模型LeaveType中定义,它具有Keys {CompanyCode,WorkGroup,LeaveTypeCode}。

现在我如何通过在代码优先使用LeaveApplicationHeader模型字段将LeaveApplicationDetails模型与LeaveType模型链接?

修改: 示例C#代码:

public class LeaveTypes
{
    [Key, Column(Order = 0)]
    public int CompCode { get; set; }

    [Key, Column(Order = 1)]
    public int WrkGrp { get; set; }

    [Key, Column(Order = 2)]
    [Required]
    [StringLength(2)]
    public string LeaveTypeCode { get; set; }

    [StringLength(50)]
    public string LeaveTypeName { get; set; }
}

public class LeaveApplicationHeader
{
    [Key]
    public int LeaveAppId { get; set; }

    public int EmpUnqId { get; set; }
    [ForeignKey("EmpUnqId")]
    public Employees Employee { get; set; }

    public int CompCode { get; set; }
    [ForeignKey("CompCode")]
    public Company Company { get; set; }

    public int WrkGrp { get; set; }
    [ForeignKey("CompCode, WrkGrp")]
    public WorkGroups WorkGroup { get; set; }

}


public class LeaveApplicationDetails
{
    [Key, Column(Order = 0)]
    public int LeaveAppId { get; set; }

    [Key, Column(Order = 1)]
    public int LeaveAppItem { get; set; }

    // HOW TO REFER LeaveTypeCode here?
    // Using CompCode and WrkGroup of LeaveApplicationHeader?

}

1 个答案:

答案 0 :(得分:0)

  

现在我如何通过在代码优先使用LeaveApplicationHeader模型字段将LeaveApplicationDetails模型与LeaveType模型链接?

你做不到。出于同样的原因,您无法在数据库中拥有外键。将所有外键列放在一个表上(例如,通过创建LeaveApplicationHeader的键(CompCode,WrkGrp,LeaveAppId),或者在LeaveApplicationDetail上写一个属性,根据需要查询描述。