【问题标题】:User Roles not updating for entity framework in customroleprovidercustomroleprovider 中的实体框架的用户角色未更新
【发布时间】:2012-03-12 22:08:58
【问题描述】:

我有一个应用,用户和角色之间的关系如下:

modelBuilder.Entity<User>()
                .HasMany(c => c.Roles)
                .WithMany(p => p.Users)
                .Map(
                   m => {
                       m.MapLeftKey("UserId");
                       m.MapRightKey("RoleId");
                       m.ToTable("UserRole");
                   });

相当标准的东西。我有一个 customRoleProvider 设置如下:

    public class CustomRoleProvider : RoleProvider
        {
            private readonly IUnitOfWork _unitOfWork;

            public CustomRoleProvider()
            {
                _unitOfWork = DependencyResolver.Current.GetService<IUnitOfWork>();
            }

            public CustomRoleProvider(IUnitOfWork unitOfWork)
            {
                _unitOfWork = unitOfWork;
            }

...

            public override string[] GetRolesForUser(string username)
            {
                var user = _unitOfWork.UserRepository.GetUser(username);

                var roles = from r in user.Roles
                            select r.Name;

                if (roles != null)
                    return roles.ToArray();
                else
                    return new string[] { };
            }

            public override bool IsUserInRole(string username, string roleName)
            {
                var user = _unitOfWork.UserRepository.GetUser(username);

                var roles = from r in user.Roles
                            select r.Name;

                return roles.Any(r => r.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
            }
    ...

        }

这似乎工作正常并返回角色正常但有一个例外。如果您通过以下方式添加角色:

user.Roles.Add(role);

            _db.SaveChanges();

代码没有找到新角色,直到你重新启动应用程序,这是不好的。

通过一些实验,我发现如果我在需要时实例化 unitOfWork,就会找到完整的角色列表:

public override string[] GetRolesForUser(string username)
            {
                  **var unitOfWork = new UnitOfWork();**

                var user = unitOfWork.UserRepository.GetUser(username);

                var roles = from r in user.Roles
                            select r.Name;

                if (roles != null)
                    return roles.ToArray();
                else
                    return new string[] { };
            }

但是我真的不想这样做。

有人知道如何解决这个问题吗?

【问题讨论】:

  • 是_unitOfWork.Save();调用 .SaveChanges()?
  • 当然是。抱歉我有一个错误更新了
  • 如果调用 ObjectContext.Refresh 会怎样?
  • 这是一个 dbcontext,我没有为它找到刷新?
  • 虽然需要刷新用户角色,但我有点明白你的意思

标签: asp.net-mvc entity-framework


【解决方案1】:

检查您是否在用户的 cookie 中缓存您的角色。尝试将cacheRolesInCookie="false" 添加到web.config 的roleManager 节点。

【讨论】:

  • 显然 Roles 集合上有一个方法可以删除 cookie 并强制重新构建它? msdn.microsoft.com/en-us/library/…
  • 已检查。这绝对不是导致问题的 cookie,因为它不断进入我的 GetrolesForUser 方法
猜你喜欢
  • 2018-08-14
  • 1970-01-01
  • 2015-11-02
  • 2023-01-24
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多