Ef core 5 many to many filter

十年热恋 提交于 2021-01-28 09:02:05

问题


This is my query

 public async Task<IEnumerable<Menu>> GetMenuByRolesAsync(string[] roles)
        {
    var result= await _context.Menus//.Include(o => o.Parent)
                                     .Include(m => m.Childrens)
                                     .ThenInclude(m => m.Childrens)
                                     .Include(m => m.Roles.Where(r => roles.Contains(r.Name)))   --it is not filtering basd on roles                          
                                     .Where(m => m.ParentId == null)
                                     .ToListAsync();
}

It is generating below query

-- @__roles_0='System.String[]' (DbType = Object)
SELECT m.id, m.icon, m.name, m.parent_id, m.url, t.role_id, t.menu_id, t.id, t.concurrency_stamp, t.name, t.normalized_name
FROM security.menu AS m
LEFT JOIN (
    SELECT r.role_id, r.menu_id, r0.id, r0.concurrency_stamp, r0.name, r0.normalized_name
    FROM security.role_menu AS r
    INNER JOIN security.role AS r0 ON r.role_id = r0.id
    WHERE r0.name = ANY (@__roles_0) OR ((r0.name IS NULL) AND (array_position(@__roles_0, NULL) IS NOT NULL))
) AS t ON m.id = t.menu_id
WHERE (m.parent_id IS NULL)
ORDER BY m.id, t.role_id, t.menu_id, t.id

This is Many to many configuration // many to many

    builder.HasMany(r => r.Menus)
           .WithMany(r => r.Roles)
           .UsingEntity<RoleMenu>(
              j => j
                  .HasOne(rm => rm.Menu)
                  .WithMany(m => m.RoleMenus)
                  .HasForeignKey(rm => rm.MenuId),
              j => j
                  .HasOne(rm => rm.Role)
                  .WithMany(r => r.RoleMenus)
                  .HasForeignKey(rm => rm.RoleId),
              j =>
              {
                  j.ToTable("role_menu", schema: "security");                                                 
                  j.HasKey(rm => new { rm.RoleId, rm.MenuId });
              });

i need to filter menus based on roles..But it is not filtering based on roles..Am getting all the roles..I checked generated query..Please let me know what is the issue..


回答1:


You are mixing filtered include with entity filtering.

Filtered include

.Include(m => m.Roles.Where(r => roles.Contains(r.Name)))

just filters the items in the related collection (menu roles in this case).

In order to filter the entity set (menus in this case), you need to replace it with the usual Where oparator, which for the desired filtering will be

.Where(m => m.Roles.Any(r => roles.Contains(r.Name)))


来源:https://stackoverflow.com/questions/65804252/ef-core-5-many-to-many-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!