我有以下型号:
用户:
public class User : IEntity, INamedType
{
public virtual int UserId { get; set; }
[Column(TypeName = "varchar")]
[StringLength(100)]
public virtual string UserName { get; set; }
[Column(TypeName = "varchar")]
[StringLength(100)]
public virtual string FirstName { get; set; }
[Column(TypeName = "varchar")]
[StringLength(100)]
public virtual string LastName { get; set; }
[Column(TypeName = "varchar")]
[StringLength(200)]
public virtual string EmailAddress { get; set; }
public int AreaId { get; set; }
[Column(TypeName = "varchar")]
[StringLength(64)]
public string CreatedByUserName { get; set; }
public DateTime CreatedDateTime { get; set; }
[Column(TypeName = "varchar")]
[StringLength(64)]
public string LastModifiedByUserName { get; set; }
public DateTime? LastModifiedDateTime { get; set; }
public bool Active { get; set; }
//Navigation properties
public virtual Area Area { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
作用:
public class Role : IEntity
{
public int RoleId { get; set; }
[Column(TypeName = "varchar")]
[StringLength(100)]
public string Name { get; set; }
[Column(TypeName = "varchar")]
[StringLength(1000)]
public string Description { get; set; }
[Column(TypeName = "varchar")]
[StringLength(64)]
public string CreatedByUserName { get; set; }
public DateTime CreatedDateTime { get; set; }
[Column(TypeName = "varchar")]
[StringLength(64)]
public string LastModifiedByUserName { get; set; }
public DateTime? LastModifiedDateTime { get; set; }
//Navigation Properties
public ICollection<User> Users { get; set; }
}
的UserRole:
public class UserRole
{
public int UserId { get; set; }
public int RoleId { get; set; }
//Navigation properties
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}
我也有一个使用此方法的CustomRoleProvider:
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[] { };
}
所以这一切都正常,直到在UserRole
表中添加或删除条目。对于User
,此记录与通过添加UserRole
行添加的新角色相关,但GetRolesForUser
方法中没有。同样,如果删除UserRole
条记录,则Role
会继续记录。
但是,如果发生IISReset,那么所有正确的记录都会通过。
任何人都知道为什么会这样,以及如何纠正?
答案 0 :(得分:0)
UserRole
实体类与EF为多对多关系创建的连接表冲突。
您应该删除UserRole
实体,或将User
和Role
中的关系映射到加入实体
public class User : IEntity, INamedType
{
public virtual int UserId { get; set; }
public virtual ICollection<UserRole> Roles { get; set; }
}
public class Role : IEntity
{
public int RoleId { get; set; }
//Navigation Properties
public ICollection<UserRole> Users { get; set; }
}