EFCore中自引用的實體類設計

一个人走在路上發表於2024-08-17

案例:以部門(為主)-----部門下面又分1部、2部、3部等,1部下面又分為1組,2組,3組等這種結構像這樣的設計型別應該用自引用來設計下面用用程式碼來實現:
///


/// Department class
///

public class Department
{
///
/// 部門 Id
///

public int Id { get; set; }
///
/// 部門名稱 Name
///

public string Name { get; set; }
///
/// Manager
///

public Department Deparparent { get; set; }
///
///部門下屬
///

public ICollection Children { get; set; } = new List();
}

以下是實體模型關係配置類
public class DepartmentConfig : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder builder)
{
builder.ToTable("Department");
builder.Property(d => d.Id).UseIdentityColumn();
builder.Property(d => d.Name).HasMaxLength(50).IsRequired();
builder.HasOne(d => d.Deparparent).WithMany(a => a.Children);//這句配置是重點
}
}

相關文章