包括没有映射的相关数据 table
Include related data without mapping table
我有 2 个模型(Users
和 Teams
)通过第三个映射模型(TeamUsers
)多对多关联。
现在我想获得团队并加入用户,而不显示返回的映射表内容 JSON。
例如:
var teams = await _context
.Teams
.Include(t => t.TeamUsers)
.ThenInclude(u => u.User)
.ToListAsync();
returns:
[
{
"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": []
}
]
}
]
一种创建视图模型和 select 属性的方法。
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;
我有 2 个模型(Users
和 Teams
)通过第三个映射模型(TeamUsers
)多对多关联。
现在我想获得团队并加入用户,而不显示返回的映射表内容 JSON。
例如:
var teams = await _context
.Teams
.Include(t => t.TeamUsers)
.ThenInclude(u => u.User)
.ToListAsync();
returns:
[
{
"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": []
}
]
}
]
一种创建视图模型和 select 属性的方法。
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;