EF中一對多的自反關係設置

        對於通常的目錄樹,一般就是一對多的自反關係,通常會有一個PID,引用於這個ID,實體類代碼相似於下: html

public partial class Catalog
{
    public Catalog()
    {
        this.References = new List<Reference>();
        this.Children = new List<Catalog>();
    }
 
    public string CatalogID { get; set; }
    public string CatalogName { get; set; }
    public string CatalogPID { get; set; }
    public ICollection<Reference> References { get; set; }
 
    public virtual Catalog Parent { get; set; }
    public virtual ICollection<Catalog> Children { get; set; }
}

        實體類中會有一個孩子節點的集合,而後有一個父節點的實體;Map文件映射以下:app

public CatalogMap()
{
    // Primary Key
    this.HasKey(t => t.CatalogID);
 
    // Properties
    this.Property(t => t.CatalogID)
        .IsRequired()
        .HasMaxLength(36);
 
    this.Property(t => t.CatalogName)
        .HasMaxLength(100);
 
    this.Property(t => t.CatalogPID)
       .IsOptional();
 
    // Table & Column Mappings
    this.ToTable("Catalog");
    this.Property(t => t.CatalogID).HasColumnName("CatalogID");
    this.Property(t => t.CatalogID).HasColumnName("CatalogPID");
    this.Property(t => t.CatalogName).HasColumnName("CatalogName");
 
 
    //Relationships
    //this.HasMany(t => t.References)
    //    .WithOptional(t => t.Catalog)
    //    .HasForeignKey(d => d.CatalogID);
 
    this.HasOptional(t => t.Parent)
        .WithMany(t => t.Children)
        .HasForeignKey(d => d.CatalogPID);
}

       必定要注意如下的這段代碼:ui

this.Property(t => t.CatalogPID)
            .IsOptional();

        它的意思是容許這個外鍵爲空,由於通常狀況下,根結點的父ID通常都會爲空。若是設置爲必須的話,那麼根結點的父ID就不知道設置成什麼值了。不然的話,在程序中就會報錯:「because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be 1」.this

       參考資料:http://www.cnblogs.com/libingql/p/3353112.html#5spa

相關文章
相關標籤/搜索