如何将第二个外键添加到EF属性中,该属性已经是复合外键的一部分

时间:2016-03-30 15:57:36

标签: c# entity-framework foreign-key-relationship composite-primary-key audit-trail

我正在尝试通过创建该表的副本来创建表的审计跟踪,该表包含一个额外的日期作为主键的一部分。

以下是我想要做的简化示例。

a diagram of the relationships I want to create in some EF entities

我的实体代码目前如下:

public class Person
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
}

public class GiftIdea
{
    [Key, Column(Order:0), ForeignKey("Person")]
    public int PersonID { get; set; }
    [Key, Column(Order:1)]
    public DateTime RecordDate { get; set; }
    public string Description { get; set; }
    public string Occasion { get; set; }

    //Linked Entities
    public virtual Person Person { get; set; }
}

public class AuditGiftIdea
{
    [Key, Column(Order:0), ForeignKey("GiftIdea")]
    public int PersonID { get; set; }
    [Key, Column(Order:1), ForeignKey("GiftIdea")]
    public DateTime RecordDate { get; set; }
    [Key, Column(Order:2)]
    public DateTime AuditRecordDate { get; set; }
    public string Description { get; set; }
    public string Occasion { get; set; }

    //Linked Entities
    public virtual GiftIdea GiftIdea { get; set; }
}

最终,我希望能够从AuditGiftIdea对象引用Person,而无需通过附加的GiftIdea。

所以我尝试了这个:

public class AuditGiftIdeas
{
    [Key, Column(Order:0), ForeignKey("GiftIdea"), ForeignKey("Person")] //Extra Foreign Key
    public int PersonID { get; set; }
    [Key, Column(Order:1), ForeignKey("GiftIdea")]
    public DateTime RecordDate { get; set; }
    [Key, Column(Order:2)]
    public DateTime AuditRecordDate { get; set; }
    public string Description { get; set; }
    public string Occasion { get; set; }

    //Linked Entities
    public virtual GiftIdea GiftIdea { get; set; }
    public virtual Person Person { get; set; } //Access to desired object
}

但我得到的编译时间错误为#34; Duplicate' ForeignKey'属性"

如何完成此设置?

1 个答案:

答案 0 :(得分:1)

您无法通过数据注释执行此操作,因为ForeignKeyAttribute标有AllowMultiple = false

但您可以使用Fluent API进行配置:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<AuditGiftIdea>()
        .HasRequired(t => t.Person).WithMany()
        .HasForeignKey(t => t.PersonID)
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}

请注意,您需要关闭级联删除,因为新的FK正在创建循环级联路径,如果您不这样做,EF将抛出错误。这反过来意味着您可能在删除Person记录时遇到问题 - 您必须手动删除AuditGiftIdea表中的相关记录。所以在介绍FK之前要仔细考虑。