2013-01-03 46 views
1

我有實體實體如何在父子關係中允許ForeignKey?

/// <summary> 
/// The greoup. 
/// </summary> 
public class Group 
{ 
    #region Public Properties 

    /// <summary> 
    /// Gets or sets the group id. 
    /// </summary> 
    [Key] 
    public int GroupId { get; set; } 

    /// <summary> 
    /// Gets or sets the parent group id. 
    /// </summary>  
    public int ParentGroupId { get; set; } 

    /// <summary> 
    /// Gets or sets the active. 
    /// </summary> 
    public int Active { get; set; } 

    /// <summary> 
    /// Gets or sets the description. 
    /// </summary> 
    public string Description { get; set; } 

    /// <summary> 
    /// Gets or sets the group guid. 
    /// </summary> 
    public Guid GroupGuid { get; set; } 

    /// <summary> 
    /// Gets or sets the order weight. 
    /// </summary> 
    public int OrderWeight { get; set; } 

    /// <summary> 
    /// Gets or sets the parent group. 
    /// </summary> 
    [ForeignKey("ParentGroupId")] 
    public virtual Group ParentGroup { get; set; } 

    /// <summary> 
    /// Gets or sets the groups. 
    /// </summary> 
    public virtual ICollection<Group> Groups { get; set; } 

    #endregion 
} 

我怎樣才能允許退出外鍵。因爲當我嘗試添加Group時,ParentGroupId = 0。我得到異常

無法確定依賴操作的有效順序。由於外鍵約束,模型要求或商店生成的值,可能會存在依存關係。

+0

你是什麼意思的「退出外鍵」? GroupId是標識列嗎?你能顯示引發異常的代碼嗎? –

回答

0

您正在使用此結構在數據庫中創建自引用表。所以ParentGroupId必須是空的。根節點不能有父節點,但由它產生的所有節點都會有父節點,所以需要使ParentGroupId爲空。

+0

編號根ParentGroupId必須爲0 – Greg

+0

根據您的代碼,每個節點必須有一個父代,那麼根必須也有一個父代,因爲根沒有父代,所以這是不可能的。因此需要它是可空的。 –

相關問題