简体   繁体   English

ASP.NET 核心EF参考回路

[英]ASP.NET Core EF reference loop


I have an ASP.NET Web API project.我有一个 ASP.NET Web API 项目。
Database: PostgreSQL数据库:PostgreSQL
I have 2 objects - User and Group.我有 2 个对象 - 用户和组。 It is a many to many relation, thus there are 3 classes - User, Group and UserGroup.它是多对多关系,因此有 3 个类 - 用户、组和用户组。 The problem comes when I want to get all the groups the user is in - the reference loop.当我想获取用户所在的所有组 - 参考循环时,问题就来了。 I just need the Groups, not the users in them as well.我只需要组,而不是其中的用户。 I'm not sure how to achieve that, for now, I'm just using this:我不知道如何实现这一点,现在,我只是使用这个:

var user = await _context.Users.Include(u => u.UserGroups).ThenInclude(ug => ug.Group)
                .FirstOrDefaultAsync(u => u.Email == email.ToLower());
            var userGroups = user.UserGroups.Select(ug =>
            {
                var group = ug.Group;
                group.UserGroups = null;
                return group;
            }).ToArray();

To be clear, my problem is not the JSON error, I just don't want those objects to be included.需要明确的是,我的问题不是 JSON 错误,我只是不希望包含这些对象。
I thought, that selecting individual columns in the database could help, but I don't think it's a good approach since you'd have to change it every time you change the objects.我认为,在数据库中选择单个列可能会有所帮助,但我认为这不是一个好方法,因为每次更改对象时都必须更改它。
EDIT1编辑1
What I need to get out is a User with an array of his groups.我需要得到的是一个拥有一组组的用户。
EDIT2编辑2
The output of the code shown above is this:上图代码的output是这样的:

{
  "id": "7e445bd2-4257-40ad-bed1-be975e562fa0",
  "registeredAt": "2019-10-06T16:51:39.235955",
  "email": "kozak.vaclav@kobrasoft.cz",
  "firstName": "Vaclav",
  "lastName": "Kozak",
  "locale": "cs-CZ",
  "groups": [
    {
      "id": "7e445bd2-4257-40ad-bed1-be975e562fa0",
      "groupType": 0,
      "userGroups": null
    }
  ]
}

, which is quite what I want, but I'm just looking for some more reasonable solution than mine. ,这正是我想要的,但我只是在寻找一些比我更合理的解决方案。

Another way is to search through the association table and select required groups.另一种方法是搜索关联表和 select 所需的组。 Lazy loading is not used.不使用延迟加载。

var userGroups = await _context.UserGroup
.Include(x => x.User)
.Include(x => x.Group)
.AsNoTracking()
.Where(x => x.User.Email.ToLower() == e)
.Select(x => x.Group)
.ToListAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM