包含没有映射表的相关数据(Include related data without mapping table)

编程入门 行业动态 更新时间:2024-10-23 08:31:31
包含没有映射表的相关数据(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

本文发布于:2023-07-26 00:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1268341.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Include   related   table   mapping

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!