【发布时间】:2014-09-09 11:29:37
【问题描述】:
在 Identity 2.0.0 中,我们在 ApplicationUser 中有 Roles 导航属性,类型为 IdentityUserRoles 我们在 IdentityRole 中具有相同类型的 IdentityUserRoles 的用户导航属性
在这里
namespace Microsoft.AspNet.Identity.EntityFramework
{
// Summary:
// EntityType that represents a user belonging to a role
//
// Type parameters:
// TKey:
public class IdentityUserRole<TKey>
{
public IdentityUserRole();
// Summary:
// RoleId for the role
public virtual TKey RoleId { get; set; }
//
// Summary:
// UserId for the user that is in the role
public virtual TKey UserId { get; set; }
}
}
所以,当我遍历 context.Users 时,我只能得到 RoleId
有没有办法在 ApplicationUser 和 ApplicationRole 之间建立标准的多对多映射?
我希望能够做这样的事情
foreach (var user in ApplicationDbContextInstance.Users)
{
List<ApplicationRole> UserRoles = user.Roles.ToList();
/*
some logic ...
*/
}
更新:
在解决这个问题后,我找到了适合我的情况的解决方案。 也许它没有那么优雅,但在我的情况下,我必须使用额外的导航属性扩展 IdentityUserRole
我已将 IdentityUserRole 扩展到 ApplicationUserRole 并在所有解决方案中进行适当的更改。 这是我的新 IdentityUserRole:
public class ApplicationUserRole : IdentityUserRole<string>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
public virtual ICollection<GeoSectorForUser> GeoSectors { get; set; }
}
现在我可以像这样让所有用户担任特定角色:
foreach(ApplicationRole role in db.Roles){
List<ApplicationUser> users = role.Users.Select(s => s.User).ToList();
}
在我的情况下,需要 AplicationUserRole 来存储其他导航属性,以便解决方案适合我。 但我仍然想知道如何在 IdentityUser 和 IdentityRole 之间创建干净的多对多关系
【问题讨论】:
-
IdentityUserRole是已经提供多对多关系的中间对象。所以IdentityUserIdentityUserRole`IdentityRole' -
您的更新对我不起作用。尝试创建新迁移时出现异常。
标签: c# asp.net-identity-2