简体   繁体   English

如何在实体框架中使用链接表

[英]How to use Linking Table in Entity Framework

I've been trying to puzzle out how to use entity framework to return a query like so我一直在努力弄清楚如何使用实体框架来返回这样的查询

{
  UserID: 1,
  Roles: ["RoleOne","RoleTwo","RoleThree"]
}

Where my tables are as such:我的桌子在哪里:

    public class User
    {
        public int? ID { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
    }

    public class UserRoles
    {
        public int ID { get; set; }
        public int UserID{ get; set; }
        public int RoleID { get; set; }
    }

    public class Roles
    {
        public int ID { get; set; }
        public string? Name { get; set; }
    }

I've tried joins, and looked into creating a relationship in the classes, as well as trying to figure out groupBy, but all with no luck.我试过加入,并研究了在类中创建关系,以及试图找出 groupBy,但都没有运气。

If I'm missing something obvious please let me know!如果我遗漏了一些明显的东西,请告诉我! Thanks!谢谢!

Your response model should be like this:您的回复 model 应该是这样的:

public class RespModel
{
    public int UserID { get; set; }
    public List<string> Roles { get; set; }
}

And your query could be like this:你的查询可能是这样的:

 var query = from userRolesRec in _context.UserRoles
             join user in _context.User on userRolesRec.UserID equals user.ID ?? 0
             select new RespModel
             {
               UserID = user.ID,
               Roles = (from roles in _context.Roles 
                        where userRolesRec.RoleID == roles.ID
                        select roles.Name).ToList()
             }

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

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