精巧的多对多结果

时间:2018-08-01 02:41:34

标签: c# dapper

我有实体ApplicationUser,ApplicationRole,ApplicationPermission。

public class ApplicationUser
{
    public guid id_user {get;set;}
    public string name {get;set;}
    public IList<ApplicationRole> Roles { get; set; }
    public IList<ApplicationPermission> Permissions { get; set; }
}

public class ApplicationRole
{
    public guid id_role {get;set;}
    public string name {get;set;}
    public IList<ApplicationUser> Users { get; set; }
    public IList<ApplicationPermission> Permissions { get; set; }
}

public class ApplicationPermission
{
    public guid id_permission {get;set;}
    public string name {get;set;}
    public IList<ApplicationUser> Users { get; set; }
    public IList<ApplicationRoles> Roles { get; set; }
}

我将查询与多个SQL分开,如下所示。

SELECT u.*, r.* FROM ApplicationUser u 
jOIN ApplicationUserRole ur ON u.id_user = ur.id_user 
jOIN ApplicationRole r ON ur.id_role = r.id_role;

SELECT u.*, p.* FROM ApplicationUser u
JOIN ApplicationUserPermission up ON u.id_user = up.id_user 
JOIN ApplicationPermission p ON up.id_permission = p.id_permission 

ApplicationUser和应用程序角色之间的关系为M:N。 ApplicationRole和ApplicationPermission之间的关系为M:N。

例如,一个用户可能拥有一个具有许多权限的角色。

我的目标是返回ApplicationUser表中的所有用户列表,并映射具有角色和权限的映射。

我已经做完了,直到下面的代码,并且不确定如何继续或是否正确。

public IEnumerable<ApplicationUser> All()
{
 var query = "SELECT u.*, r.* FROM ApplicationUser u " +
 "JOIN ApplicationUserRole ur ON u.id_user = ur.id_user " +
 "JOIN ApplicationRole r ON ur.id_role = r.id_role;" +
 "SELECT u.*,up.*, p.* FROM ApplicationUser u " +
 "JOIN ApplicationUserPermission up ON u.id_user = up.id_user" +
 "JOIN ApplicationPermission p ON up.id_permission = p.id_permission;";

  var results = Connection.QueryMultiple(
                query,
                transaction: Transaction);

  var userRoles = results.Read<ApplicationUser, ApplicationRole, ApplicationUser>(splitOn: "id_role",buffered:true).ToList();
  var userPermission = results.Read<ApplicationUser,ApplicationPermission,ApplicationUser>(splitOn: "id_permission", buffered: true).ToList();
}

0 个答案:

没有答案