zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    redis使用lua脚本遇到的问题
    redis使用scan count 返回数量不准确
    window系统下搭建本地的NuGet Server
    windows10使用docker发布.netcore程序
    windows10使用docker安装mysql
    windows10搭建redis4.0集群
    windows10配置redis主从复制
    windows10安装redis4.0
    mysql 共享排他锁
    mysql drop表以后恢复数据
  • 原文地址:https://www.cnblogs.com/xiaoxiangfeizi/p/3572596.html
Copyright © 2011-2022 走看看