我可能以错误的方式看待这个问题,但我在 EF Core 3.1 中有一个基本的多对多代码优先设置,其中 Department <-> DepartmentDay <-> Day。
modelBuilder.Entity<DepartmentDay>(entity =>
{
entity.HasKey(dd => new { dd.DepartmentId, dd.DayId });
entity.HasOne(dp => dp.Day)
.WithMany(p => p.DepartmentDays)
.HasForeignKey(d => d.DayId);
entity.HasOne(dp => dp.Department)
.WithMany(p => p.DepartmentDays)
.HasForeignKey(d => d.DepartmentId);
});
第一个问题:这种关系是可选的,我可以有几天不与部门联系吗?我需要这个,因为这与营业时间有关,并且希望有一个影响所有部门的通用日期,而不必与所有部门建立特定的联系。但正如我在一开始所说的那样,我可能会以错误的方式看待这个问题。
第二个问题:如果第一个问题是真实有效的设置,我如何让那些日子没有连接到 Linq 查询中的部门?
到目前为止我所拥有的是(编辑:将 allDays 从 Hashset 更改为 List。)
var allDays = await _context.Days.ToListAsync();
var allDepartmentDays = _context.DepartmentDays.Select(dd => dd.DayId).ToHashSet();
var genericDays = allDays.Where(d => !allDepartmentDays.Contains(d.Id));
还是在这里使用原始查询来提高性能更好?
SELECT Id
FROM Day
WHERE Id NOT IN (SELECT DayId FROM DepartmentDay)
编辑 2:包括整个数据模型
public class Department
{
public int Id { get; set; }
public int DepartmentNr { get; set; }
public string Service { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Postal { get; set; }
public string City { get; set; }
public string Url { get; set; }
public string MapUrl { get; set; }
public DateTime Created { get; set; }
public string CreatedBy { get; set; }
public DateTime? Updated { get; set; }
public string UpdatedBy { get; set; }
public ICollection<DepartmentPeriod> DepartmentPeriods { get; set; }
public ICollection<DepartmentDay> DepartmentDays { get; set; }
}
public class DepartmentDay
{
public int DepartmentId { get; set; }
public int DayId { get; set; }
public Department Department { get; set; }
public Day.Models.Day Day { get; set; }
}
public class Day
{
public int Id { get; set; }
public int PeriodId { get; set; }
public string Service { get; set; }
public string City { get; set; }
public DateTime? Date { get; set; }
public DayOfWeek? DayOfWeek { get; set; }
public DateTime? OpenTime { get; set; }
public DateTime? CloseTime { get; set; }
public bool IsClosed { get; set; }
public string Description { get; set; }
public DateTime Created { get; set; }
public string CreatedBy { get; set; }
public DateTime? Updated { get; set; }
public string UpdatedBy { get; set; }
public ICollection<DepartmentDay> DepartmentDays { get; set; }
public virtual Period.Models.Period Period { get; set; }
}
modelBuilder.Entity<Day>(entity =>
{
entity.HasOne(d => d.Period)
.WithMany(p => p.Days)
.HasForeignKey(d => d.PeriodId);
});
最初的问题中没有包含另一个关系,它可以回答我的第一个问题,即 Department 1-M DepartmentPeriod M-1 Period 1-1 Day。因此,Day 表中会有几天与 DepartmentDay 无关,而与 Period 无关,对吗?