簡體   English   中英

實體框架多個多對多的查詢

[英]entity framework multiple many to many queries

我有一個簡單的安全模型,其中有:

  • 用戶
  • 角色
  • 路徑

以及這些表之間的多對多鏈接,因此用戶可以使用角色,也可以將角色添加到路徑中。 我正在嘗試編寫一個函數,以便從用戶名和路徑中返回一個bool值,具體取決於用戶是否可以訪問該路徑。 我如何使用實體框架執行此操作? 我目前有:

var rolesForUser = _entities.Users
         .Include("Roles")
         .Where(u => u.Login.Equals(username))
         .Select(u => u.Roles);

if(rolesForUser.Count() == 0) return false;

var authentications = _entities.WebPaths
         .Where(p => p.Path == path)
         .WhereIn(p => p.Roles, rolesForUser);

return (authentications.Count() > 0);

它使用擴展方法WhereIn ,但是這只能在靈長類動物上進行比較,因此目前不起作用。 歡迎任何建議。

你可以用PredicateBuilder做到這一點。

脫離我的頭頂:

var predicate = PredicateBuilder.False<WebPath>();
foreach (var role in from roles in rolesForUser 
                     from r in roles.Role
                     select r)
{
  predicate = predicate.Or (p => p.roles.Any(r => r.Id == role.Id));
}

var authentications = _entities.WebPaths.AsExpandable()
         .Where(p => p.Path == path)
         .Where(predicate);
return (authentications.Count() > 0);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM