我有两个模型(Users
和Teams
)多对多通过第三个映射模型(TeamUsers
)相关。
现在,我想获得团队并加入用户,而不在显示的JSON中显示映射表内容。
例如:
var teams = await _context
.Teams
.Include(t => t.TeamUsers)
.ThenInclude(u => u.User)
.ToListAsync();
返回:
[
{
"teamId": 1,
"name": "Dev Team",
"avatart": null,
"createdAt": "0001-01-01T00:00:00",
"teamUsers": [
{
"teamId": 1,
"userId": 1,
"user": {
"userId": 1,
"firstName": "John",
"secondName": null,
"lastName": "Doe",
"email": null,
"avatar": null,
"teamUsers": []
}
}
]
}
]
但是我想要这个:
[
{
"teamId": 1,
"name": "Dev Team",
"avatart": null,
"createdAt": "0001-01-01T00:00:00",
"teamUsers": [
{
"userId": 1,
"firstName": "christopher",
"secondName": null,
"lastName": "elstner",
"email": null,
"avatar": null,
"teamUsers": []
}
]
}
]
答案 0 :(得分:1)
创建视图模型并选择属性的一种方法。
var teams = await _context
.Teams
.Include(t => t.TeamUsers)
.ThenInclude(u => u.User)
.Select(c => new TeamViewModel
{
TeamID = c.TeamID,
Name = c.Name,
Avatart = c.Avatart,
CreatedAt = c.createdAt,
Users = c.TeamUsers.Select(u=>u.User).ToList()
}).ToListAsync();
return teams;