我有一个像下面这样的实体
public class Role
{
[Key, Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required, StringLength(30)]
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<RolePermission> Permissions { get; set; }
public bool HasPermission(String code)
{
foreach (var p in this.Permissions)
{
if (p.Permission.Code.Equals(code))
return true;
}
return false;
}
}
在控制器中,这段代码运行良好:
for (var p in db.User.Where(u => u.UserId == 1).First().Role.Permissions) { PrintToDebug(); }
但:
User ur = db.User.Where(u => u.UserId == 1).First();
ur.Role.HasPermission("Some_Code_Were_Defined");
那么Permissions
列表中HasPermission
的长度总是为零,为什么以及如何解决?