简体   繁体   English

使用Entity Framework Core查询多对多相关数据

[英]Query many-to-many related data using Entity Framework Core

I have two entities that have a many-to-many relationship. 我有两个具有多对多关系的实体。 I also have an entity between then that holds the two ID's. 然后,我还有一个实体,其中包含两个ID。 I want to load only the two main entities. 我只想加载两个主要实体。

My entities: 我的实体:

public class User 
{
    public long Id { get; set; }
    public string Email { get; set; }
    public virtual ICollection<UserRole> UserRoles { get; set; }
}

public class Role 
{
    public long Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<UserRole> UserRoles { get; set; }
}

public class UserRole 
{
    public long UserId { get; set; }
    public User User { get; set; }
    public long RoleId { get; set; }
    public Role Role { get; set; }
}

Expected JSON result: 预期的JSON结果:

{
  "Email": ...
  "Roles": [
    {"Name": ...},
    {"Name": ...},
    ...
  ] 
}

EF Core doesn't technically support M2M relationships. EF Core在技术上不支持M2M关系。 You can fake said support via a "join" entity, which connects the two sides of the relationship, as you have here with UserRole . 您可以通过“连接”实体来伪造所说的支持,该实体将关系的两端连接起来,就像在UserRole There's no way around this, unfortunately, so if you don't want to see the UserRole relationship in your results, you'll have to manually reshape the data. 不幸的是,这没有办法解决,因此,如果您不想在结果中看到UserRole关系,则必须手动调整数据的形状。 For example: 例如:

var users = await _context.Users.Select(u => new
{
    Email = u.Email,
    Roles = u.UserRoles.Select(r => r.Role)
}).ToListAsync();

Pro Tip: You don't need Include if you're selecting from relationships. 专家提示:如果要从关系中选择,则不需要“ Include EF Core is smart enough to issue joins in order to fill the data. EF Core足够聪明,可以发出联接以填充数据。

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

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