包含没有映射表的相关数据(Include related data without mapping table)
我有两个模型( Users和Teams )通过第三个映射模型( TeamUsers )与多对多相关。 现在我想要获得团队并加入用户,而不用在Retured 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": [] } ] } ]I have 2 models(Users and Teams) many-to-many related via a third mapping model(TeamUsers). Now I'd like to get the Teams and join the Users, without displaying the mapping tables content in retured JSON.
For example:
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": [] } } ] } ]but I'd like to have this:
[ { "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": [] } ] } ]最满意答案
一种创建视图模型并选择属性的方法。
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;One way to create a View Model and select the properties.
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;更多推荐
Teams,null,TeamUsers,teamUsers,teamId,电脑培训,计算机培训,IT培训"/> <meta na
发布评论