我有以下用户实体:
public class User
{
public virtual int Id { get; set; }
public virtual string Username { get; set; }
public virtual string UsernameLowercase { get { return Username.ToLowerInvariant(); } }
public virtual string Password { get; set; }
public virtual string Email { get; set; }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
if (ReferenceEquals(this, obj))
return true;
var otherUser = obj as User;
return (0 == string.CompareOrdinal(UsernameLowercase, otherUser.UsernameLowercase));
}
public override int GetHashCode()
{
return UsernameLowercase.GetHashCode();
}
}
和以下角色实体:
public class Role
{
public virtual int Id { get; set; }
public virtual string RoleName { get; set; }
public virtual string RoleNameLowercase { get { return RoleName.ToLowerInvariant(); } }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
if (ReferenceEquals(this, obj))
return true;
var otherRole = obj as Role;
return (0 == string.CompareOrdinal(RoleNameLowercase, otherRole.RoleNameLowercase));
}
public override int GetHashCode()
{
return RoleNameLowercase.GetHashCode();
}
}
因为可以为用户分配许多角色,所以我创建了第三个名为 UserInRole 的实体,如下所示:
public class UserInRole
{
public virtual User User { get; set; }
public virtual Role Role { get; set; }
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
return false;
if (ReferenceEquals(this, obj))
return true;
var other = obj as UserInRole;
return (Role == other.Role && User == other.User);
}
public override int GetHashCode()
{
return User.GetHashCode() ^ Role.GetHashCode();
}
}
我想使用流利的 nhibernate 在 UsersInRoles 表和 User 和 Role 表之间进行映射,以便当我删除用户时,UsersInRoles 表中定义的所有用户角色也会自动删除。这是我当前的 UserInRole 实体映射类:
public class UserInRoleMapping : ClassMap<UserInRole>
{
public UserInRoleMapping()
{
Table("UsersInRoles");
CompositeId().
KeyReference(x => x.User,k => k.Not.Lazy(), "UserId").
KeyReference(x => x.Role, k => k.Not.Lazy(), "RoleId");
}
}
感谢您的帮助。