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


            对于一般的目录树,通常就是一对多的自反关系,一般会有一个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

  • 相关阅读:
    题解 UVA120 【煎饼 Stacks of Flapjacks】
    信息编码表示

    二叉树
    逻辑运算&位运算
    POJ2425 Ubiquitous Religions(并查集板题)
    CF1426E Rock, Paper, Scissors 题解
    POJ2478 Farey Sequence
    dubbo+zookeeper报错 KeeperErrorCode = Unimplemented for /dubbo
    代码无法提交到GitHub: Remote URL test failed: git@github.com: Permission denied (publickey)
  • 原文地址:https://www.cnblogs.com/xiaoxiangfeizi/p/3572596.html
Copyright © 2020-2023  润新知