• code first实现自关联(树结构数据)


    实现自关联数据时,有两点须注意:

    1.外键字段必须设置为可为空的值类型(如int?;Guid?等)

    2.设置映射时不能级联删除,要设置WillCascadeOnDelete(false)

    二话不说了,直接来代码:

    一.部门实体:

    /// <summary>
            
    /// 部门名
            
    /// </summary>
            public string Name { getset; }

            /// <summary>
            
    /// 部门编号
            
    /// </summary>
            public string Code { getset; }

            /// <summary>
            
    /// 父级部门ID
            
    /// </summary>
            public Guid? ParentId { getset; }

            /// <summary>
            
    /// 部门顺序号(同级)
            
    /// </summary>
            public int Order { getset; }

            /// <summary>
            
    /// 父级部门
            
    /// </summary>
            public virtual Department ParentDepartment { getset; }

            /// <summary>
            
    /// 当前部门下的员工(不包含子部门的)
            
    /// </summary>
            public virtual ICollection<Employee> Employees { getset; }

            /// <summary>
            
    /// 当前部门的子部门(不包含子部门的下级部门)
            
    /// </summary>
            public virtual ICollection<Department> ChildrenDepartments { getset; }

    二.实体的映射配置

    public class DepartmentEntityConfig:EntityTypeConfiguration<Department>
        {
            #region 成员变量

            #endregion

            #region 构造函数

            public DepartmentEntityConfig()
            {
                this.HasKey(d => d.Id);

                this.Property(d => d.Name)
                    .IsRequired()
                    .HasMaxLength(50);

                this.Property(d => d.Code)
                    .IsRequired()
                    .HasMaxLength(10);

                this.Property(d => d.Order)
                    .IsRequired();

                this.Property(d => d.ParentId)
                    .IsOptional();

                this.HasOptional(d => d.ParentDepartment)
                    .WithMany(c => c.ChildrenDepartments)
                    .HasForeignKey(d => d.ParentId)
                    .WillCascadeOnDelete(false);
                   

                this.ToTable("Department");
            }

            #endregion

            #region 属性

            #endregion

            #region 方法

            #endregion
        }

     一定注意加红色的部分,搞了我好久

  • 相关阅读:
    implement the bucket sort and some analysis
    冪運匴
    polynomial multiplication
    WinRAR(WinZip)压缩与解压实现(C#版Window平台)
    Windows 窗体计时器事件,则不引发在 Windows 服务
    VS 2008智能提示是英文的怎么改成中文的?
    C#_SQL数据访问帮助类
    C#_DllImport用法和路径问题
    Office2003/2007/2010强力卸载工具下载
    Windows_装的是2008R2系统,在电脑属性里显示内存12G(可用4G)
  • 原文地址:https://www.cnblogs.com/wudingfeng/p/2306958.html
Copyright © 2020-2023  润新知