在我的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」的常量值,只有基本類型或者消費者在這種情況下支持類型「。
你有沒有嘗試過做的,而不是選擇角色,選擇新IdentityRole {ID =作用。Id,Name = role.Name} .ToList(); – grimurd 2014-09-25 01:41:54
你介意將其中一個答案標記爲已接受,所以不會將這個問題推到首頁上嗎? – 2017-11-27 12:49:18