【发布时间】:2019-01-09 22:20:16
【问题描述】:
我正在创建一个 ASP.NET Core Web API,但在查询上下文时遇到了问题。
Web API 连接到具有 3 个表的数据库:Employees、Events 和 Event Responsibilities。一名员工可以创建许多事件。此外,可以为许多员工分配每个事件中的许多事件的职责(因此链接事件职责表)。
员工表
+----+-----------------+
| Id | Name |
+----+-----------------+
| 1 | First Employee |
| 2 | Second Employee |
+----+-----------------+
事件表
+----+------------+---------------+
| Id | Creator_Id | Event_Name |
+----+------------+---------------+
| 1 | 1 | Random Event |
| 2 | 1 | Another Event |
+----+------------+---------------+
事件责任表
+----+-------------+----------+
| Id | Employee_Id | Event_Id |
+----+-------------+----------+
| 1 | 1 | 1 |
+----+-------------+----------+
这些模型包括...
事件模型
一个事件只能有一个员工作为创建者。 一个活动也可以有许多承担不同职责的员工。
public int Id { get; set; }
public int? CreatorId { get; set; }
public string EventName { get; set; }
public Employee Creator { get; set; }
public ICollection<EventResponsibilities> EventResponsibilities { get; set; }
员工模型
员工可以是许多事件的创建者。 员工可以在许多事件中承担责任。
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Event> Event { get; set; }
public ICollection<EventResponsibilities> EventResponsibilities { get; set; }
Event_Responsibilities 模型
多对多链接表模型。
public int Id { get; set; }
public int? EmployeeId { get; set; }
public int? EventId { get; set; }
public Employee Employee { get; set; }
public Event Event { get; set; }
我在控制器方法中运行了以下 LINQ 查询...
return _context.Event.Include(e => e.EventResponsibilities).ThenInclude(e => e.Employee);
我希望获得一个 JSON,其中包含事件的详细信息、其相应的事件职责以及该职责的相关员工。
我实际得到的是以下 json...
[
{
"Id": 1,
"CreatorId": 1,
"EventName": "Random Event",
"Creator": {
"Id": 1,
"Name": "First Employee",
"Event": [],
"EventResponsibilities": [
{
"Id": 1,
"EmployeeId": 1,
"EventId": 1
}
]
},
"EventResponsibilities": [
{
"Id": 1,
"EmployeeId": 1,
"EventId": 1,
"Employee": {
"Id": 1,
"Name": "First Employee",
"Event": [],
"EventResponsibilities": []
}
}
]
},
{
"Id": 2,
"CreatorId": 1,
"EventName": "Another Event",
"Creator": {
"Id": 1,
"Name": "First Employee",
"Event": [
{
"Id": 1,
"CreatorId": 1,
"EventName": "Random Event",
"EventResponsibilities": [
{
"Id": 1,
"EmployeeId": 1,
"EventId": 1
}
]
}
],
"EventResponsibilities": [
{
"Id": 1,
"EmployeeId": 1,
"EventId": 1,
"Event": {
"Id": 1,
"CreatorId": 1,
"EventName": "Random Event",
"EventResponsibilities": []
}
}
]
},
"EventResponsibilities": []
}
]
这不是我想要或期望的...... 如您所见,由于某种原因,Event 模型的 Creator 导航属性正在显示,即使我在查询中没有请求它,因为我没有使用 Include()。
此外,如果您查看 JSON 中的第二个返回事件(“Id”:2),即使没有 EventResponsibilities,也会返回两个 Creator Rows。我认为这不是延迟加载问题,因为导航属性不是虚拟的。
我本来希望 Creator 对象为 null 或空,因为我没有包含它。
所以我的问题是:为什么即使我没有加载/包含 Creator 导航属性也会被包含在内?另外,我也想知道如何 不是 包含相关的 Creator 数据,并且仅在 JSON 中显示 Event Responsibilities 数据。
【问题讨论】:
-
您已将您的属性声明为非虚拟的。实体框架无法创建延迟加载代理,因此会急切地加载所有内容。
标签: c# asp.net-core json.net ef-core-2.1