代码改变世界

EF中一对多的自反关系设置

2014-02-27 23:06  左眼微笑右眼泪  阅读(594)  评论(0编辑  收藏  举报

        对于一般的目录树,通常就是一对多的自反关系,一般会有一个PID,引用于这个ID,实体类代码类似于下:

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文件映射如下:

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);
}

       一定要注意以下的这段代码:

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”.

       参考资料:http://www.cnblogs.com/libingql/p/3353112.html#5