简体   繁体   中英

ASP.NET Core EF reference loop


I have an ASP.NET Web API project.
Database: PostgreSQL
I have 2 objects - User and Group. It is a many to many relation, thus there are 3 classes - User, Group and UserGroup. 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.
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
What I need to get out is a User with an array of his groups.
EDIT2
The output of the code shown above is this:

{
  "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. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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