2014-09-22 49 views
2

在我的ASP.NET MVC 5應用程序中,我想列出用戶的角色。我下載了一些似乎被破壞的樣本。基本上我想要角色ID和角色名稱的角色選定的用戶(不是當前用戶!)。無法創建類型爲'IdentityUserRole'的常量值。只支持原始類型或枚舉類型

ApplicationUser.Roles爲我提供了一個IdentityUserRole對象,只有RoleId和UserId。

ApplicationDbContext.Roles爲我提供了IdentityRole和所有應用程序角色的RoleId,RoleName等。

所以我想要的是一個結果集與兩個集合的交集,同時保留完整的角色信息,以便我可以使用它的角色ID和角色名稱。

我試過Intersect(),但沒有工作,因爲兩個對象都是不同的類型。我試過迭代的啞的風格,但有一個例外,稱該數據讀取器已經有效,因此我難倒:(

我試過LinQPad以下(用適當的conenctions和命名空間):

string UserName = "[email protected]"; 
ApplicationDbContext ctx = new ApplicationDbContext(); 
var allroles = ctx.Roles.OrderBy(r => r.Id); 
allroles.Dump(); // dumps well, 6 roles 

ApplicationUser user = ctx.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); 
var myroles = user.Roles; 
myroles.Dump();  // dumps well, 3 roles 

IEnumerable<IdentityRole> list = from roles in allroles 
    join uroles in myroles 
    on roles.Id equals uroles.RoleId 
    select roles; 
list.Dump(); // exception 

儘管查詢似乎在執行過程中沒有產生任何錯誤,但是它的轉儲不管我使用Dump()還是顯式的foreach(列表中的IdentityRole項目),我都得到的錯誤是

「無法reate一個類型爲「Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole」的常量值,只有基本類型或者消費者在這種情況下支持類型「。

+0

你有沒有嘗試過做的,而不是選擇角色,選擇新IdentityRole {ID =作用。Id,Name = role.Name} .ToList(); – grimurd 2014-09-25 01:41:54

+0

你介意將其中一個答案標記爲已接受,所以不會將這個問題推到首頁上嗎? – 2017-11-27 12:49:18

回答

0

你可以使用你嘗試這兩種方法,你來自哪裏,是存在於ApplicationUserRoles財產範圍內得到角色的組合...

var roles = ApplicationDbContext.Roles 
           .Where(ar => 
             ApplicationUser.Roles 
                 .Select(ur => 
                   ur.RoleId) 
                 .Contains(ar.RoleId)); 
+0

在LinqPad中嘗試過,但與上面相同,當我嘗試列出值時,我得到「無法創建常量值類型...」NotSupportedException。 – 2014-09-22 20:24:18

0

你可以這樣說:

var rolesList = allroles.ToList().Join(myroles.ToList(), 
             left => left.Id, 
             right => right.RoleId, 
             (left,right) => left); 

這種方式它爲我工作的不同情況。

0

這裏唯一的問題是,你沒有調用ToList()立即執行查詢的方法(所有東西都會保存在內存中)。

爲了更好地理解 - ToList()方法將IEnumerable<T>轉換爲List<T>

所以,你的代碼看起來就像這樣:

var allroles = ctx.Roles.OrderBy(r => r.Id).ToList();  
var myroles = user.Roles.ToList(); 
0

你試圖加入一個在內存中的列表,myroles,與IQueryableallroles,其產生的新的IQueryablelist。但是,這個新的IQueryable被翻譯成SQL,所以myroles也必須翻譯成SQL。這不支持非基元類型的列表。

的解決方案是將兩個IQueryable S:

var myroles = ctx.Users.Where(u => u.UserName == UserName).SelectMany(u => u.Roles); 

var list = from role in allroles 
      join urole in myroles 
      on role.Id equals urole.RoleId 
      select role; 
相關問題