在 EF Core 中,多对多关系通常需要一个包含两个导航属性的中间表,用于连接两个实体。在 Blazor 6 中,当我们尝试获取一个实体的相关数据时,如其关联的多个实体,可能发生错误。解决方法是通过使用 Include 和 ThenInclude 方法来显式地包括中间表和其关联实体,这将确保 EF Core 返回正确的数据。
以下是一个示例,其中两个实体之间有一个多对多关系:
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
// Navigation properties
public virtual ICollection Projects { get; set; }
}
public class Project
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
// Navigation properties
public virtual ICollection Employees { get; set; }
}
public class EmployeeProject
{
public int EmployeeId { get; set; }
public int ProjectId { get; set; }
// Navigation properties
public virtual Employee Employee { get; set; }
public virtual Project Project { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet Employees { get; set; }
public DbSet Projects { get; set; }
public DbSet EmployeeProjects { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure many-to-many relationship
modelBuilder.Entity()
.HasKey(ep => new { ep.EmployeeId, ep.ProjectId });
modelBuilder.Entity()
.HasOne(ep => ep.Employee)
.WithMany(e => e.Projects)
.HasForeignKey(ep => ep.EmployeeId);
modelBuilder.Entity()
.HasOne(ep => ep.Project)
.WithMany(p => p.Employees)
.HasForeignKey(ep => ep.ProjectId);
}
}
public class EmployeeService
{
private readonly MyDbContext _context;
public EmployeeService(MyDbContext context)
{
_context = context;