4

我有EdmAssociationConstraint:在從屬和主角色屬性的數量在一個關係約束此異常EF 5EdmAssociationConstraint:在從屬和主角色的屬性有關係約束的數目

我要使用數據標註

public class Task 
{ 
    [Key, Column(Order = 0)] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int TaskId { get; set;} 
    public string Name { get; set; } 
} 

public class Trigger 
{ 
    [Key, Column(Order = 0)] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int TriggerId { get; set; } 
    public string Name { get; set; } 

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

    [ForeignKey("TaskId")] 
    public virtual Task Tasks { get; set; } 
} 

public class TriggerHistory 
{ 
    [Key, Column(Order = 0)] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int TriggerHistoryId { get; set; } 

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

    [ForeignKey("TaskId")] 
    public virtual Task Task { get; set; } 

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

    [ForeignKey("TaskId")] 
    public virtual Trigger Triggers { get; set; } 

    public string Name { get; set; } 
} 

回答

7

你觸發類有COMPOSIT鍵(TriggerId,任務id)來解決這個問題。 但是,您的TriggerHistory具有僅使用TaskId屬性定義的觸發器導航屬性ForeignKey

嘗試改變ForeignKey上Triggers屬性是這樣的:

[ForeignKey("TriggerId,TaskId")] 
public virtual Trigger Triggers { get; set; } 

也許Triggers屬性應該被命名爲「觸發器」,因爲這不是觸發對象的集合。

+0

我不知道你可以在ForeignKey屬性中添加多個鍵。謝謝! – mga911