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