database - Entity Framework Core 一对多相关数据导航属性始终为空
问题描述
我觉得我在这里遗漏了一些明显的东西;我将 .Net 5 与 Entity Framework Core 一起使用。问题是外键是正确的,但是关联的导航属性总是空的,没有数据。我是否必须对 fluent 框架做一些事情,或者对我的包含做一些特别的事情?
在此示例中,我有 3 个简化实体和一个数据库上下文方法,该项目太大而无法完全包含。在该方法中,CalendarEvents
是一个DbSet
:
public class CalendarEvent: IJsonSerializable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
/// <summary>
/// Gets the personnel associated with this event
/// </summary>
public virtual List<SchedulePerson> SchedulePeople { get; set; } = new List<SchedulePerson>();
}
public class SchedulePerson : IJsonSerializable, ICloneable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int EmployeeId { get; set; }
public virtual Employee Employee { get; set; }
public virtual CalendarEvent AssociatedCalendarEvent { get; set; }
}
public class Employee : IJsonSerializable
{
[Key]
public int Id { get; set; }
public virtual List<SchedulePerson> AssociatedSchedulePeople { get; set; } = new List<SchedulePerson>();
}
public class DbContext : DbContext
{
public DbSet<CalendarEvent> CalendarEvents { get; set; }
public DbSet<SchedulePerson> SchedulePeople { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbContext(DbContextOptions<VibrationContext> options): base(options)
{
}
public CalendarEvent GetEvent(int calendarEventId)
{
var currentCalEvent = this.CalendarEvents.Where(x => x.Id == calendarEventId);
var dummy1 = currentCalEvent.FirstOrDefault();
var dummy2 = currentCalEvent.Include(calEvent => calEvent.SchedulePeople).ToList();
var dummy3 = currentCalEvent.Include(calEvent => calEvent.SchedulePeople).ThenInclude(people => people.Employee).ToList();
return currentCalEvent.FirstOrDefault();
}
}
在这种情况下Employee
是关联的导航属性,并且关联的 keyEmployeeId
是正确的。目前,我添加了额外的逻辑EmployeeId
,当我收到事件时,将根据外键手动填充每个日程表的每个员工,但我不想每次都添加这样的逻辑。如果这是不可避免的事情,那很好,但我想正确地做事,让 Entity Framework Core 尽可能多地处理。
有关其他上下文:
SchedulePerson -> CalendarEvent
是多对一的关系Employee -> SchedulePerson
是多对一的关系
换句话说,一个日历事件可以包含许多日程安排人员,但一个日程安排人员只能与一个日历事件相关联。
员工可以与许多日程安排人员相关联,但每个日程安排人员仅与一名员工相关联。
每个真人应该只有一个员工,但每个真人可以有多个SchedulePersons
。
感谢您的帮助,如果我可以提供更多信息,请告诉我。
此外,如果这些代码片段中有任何其他看起来不好或错误的地方,请告诉我。
编辑,如果我想在我的请求中获得员工,这就是我必须做的:
private void UpdateEmployeeContents(CalendarEvent calendarEvent)
{
foreach (SchedulePerson person in calendarEvent.SchedulePeople)
{
person.Employee = this.Employees.Where(x => x.Id == person.EmployeeId).FirstOrDefault();
}
}
解决方案
推荐阅读
- python - 为什么我无法从 __init__ 访问 Kivy lang 属性?
- java - 获取 API 调用 AzureDevOps 中的 IOException
- r - R plotmath 表达式以显示 ggplot 中的值范围
- python - 在 keras 中,在许多单个日期点上执行 fit() 是否与在数据集上执行 fit() 相同?
- scala - 如何从 Scala Spark 中的对象一般注册所有 udf?
- javascript - webpack 中的“_entry_return_”是什么意思?
- javascript - 删除谷歌分析
- html - Why is translateZ not being applied to the direct parent or its parent?
- ubuntu - 更新后 Gitlab-ctl 重新配置失败:未定义的方法 'downcase'
- postgresql - 日期类型的输入语法无效