学海无涯

导航

EF Core 关系配置 一对多 单向导航属性

一对多 单向导航属性

实体类:

 /// <summary>
    /// 用户
    /// </summary>
    public class User
    {
        public long Id { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }
    }

  

/// <summary>
    /// 请假申请单
    /// </summary>
    public class Leave
    {
        public long Id { get; set; }
        /// <summary>
        /// 申请人
        /// </summary>
        public User Requester { get; set; }
        /// <summary>
        /// 审批人
        /// </summary>
        public User? Approver { get; set; }
        /// <summary>
        /// 说明
        /// </summary>
        public string Remarks { get; set; }
        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime From { get; set; }
        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime To { get; set; }
        /// <summary>
        /// 状态
        /// </summary>
        public int Status { get; set; }
    }

  表结构:

 

 

 

 配置类:

public class UserConfig : IEntityTypeConfiguration<User>
    {
        public void Configure(EntityTypeBuilder<User> builder)
        {
            builder.ToTable("T_Users");
            builder.Property(m => m.Name).IsRequired().HasMaxLength(100).IsUnicode();
        }
    }

  

 public class LeaveConfig : IEntityTypeConfiguration<Leave>
    {
        public void Configure(EntityTypeBuilder<Leave> builder)
        {
            builder.ToTable("T_Leaves");
            //单向导航,仅需在“多端”有申明导航属性
            //无主从关系
            //单向导航配置:仅需在WithMany方法中不指定属性即可
            builder.HasOne(m => m.Requester).WithMany();
            builder.HasOne(m => m.Approver).WithMany();
        }
    }

  

posted on 2022-09-29 16:58  宁静致远.  阅读(77)  评论(0编辑  收藏  举报