我需要检索特定角色的所有用户,我认为应该简单地使这是问题。但是,这是问题。
Applicationuser的角色导航属性不是角色列表(IdentityRole),而是链接用户和角色的中间表(IdentitySerroles)的集合。因此,这是我拥有的代码,但它不起作用。
[HttpPost]
[Authorize(Roles = "Admin, Recepcionista, Orientador")]
public ActionResult SearchResults(SearchCriteriaViewModel criteria)
{
List<SearchResultViewModel> results = new List<SearchResultViewModel>();
var clients = new List<ApplicationUser>();
using (var context = new ApplicationDbContext())
{
IdentityUserRole role = new IdentityUserRole();
var tempRole = (from _role in context.Roles
where _role.Name == "client"
select _role).FirstOrDefault();
role.Role = tempRole;
clients = (from client in context.Users
where client.Email.Contains(criteria.SearchCriteria)
|| client.FirstName.Contains(criteria.SearchCriteria)
|| client.MiddleName.Contains(criteria.SearchCriteria)
|| client.LastName.Contains(criteria.SearchCriteria)
|| client.SecondLastName.Contains(criteria.SearchCriteria)
|| client.UserName.Contains(criteria.SearchCriteria)
&& client.Roles.Contains(role)
select client).ToList();
}
foreach (var client in clients)
{
results.Add(new SearchResultViewModel()
{
Email = client.Email,
FirstName = client.FirstName,
MiddleName = client.MiddleName,
LastName = client.LastName,
SecondLastName = client.SecondLastName,
UserName = client.UserName
});
}
SearchClientViewModel model = new SearchClientViewModel();
model.SearchResults = results;
return View("Index", model);
}
linq抛出以下异常
类型"系统。 mscorlib.dll,但未在用户代码中处理
其他信息:无法创建类型的常数值 'Microsoft.aspnet.Identity.entityFramework.IdentityUserrole'。仅有的 在这种情况下支持原始类型或枚举类型。
如何做到这一点,为什么导航属性不是角色集合,这可能是我们需要报告的错误?
错误消息很清楚:您在收集非主要对象时无法调用Contains
。
尝试以下内容:
clients = (from client in context.Users
where client.Email.Contains(criteria.SearchCriteria)
|| client.FirstName.Contains(criteria.SearchCriteria)
|| client.MiddleName.Contains(criteria.SearchCriteria)
|| client.LastName.Contains(criteria.SearchCriteria)
|| client.SecondLastName.Contains(criteria.SearchCriteria)
|| client.UserName.Contains(criteria.SearchCriteria)
&& client.Roles.Select(r => r.Name).Contains("client")
select client).ToList();
我敢肯定,身份框架中有一个API可以这样做。但是除了您的例外,请尝试:
&& client.Roles.Count(r => r.Name == "client") > 0