在现有数据库上流畅地休眠多对多关系

本文关键字:休眠 关系 数据库 | 更新日期: 2023-09-27 18:31:00

我正在使用Fluent NHibernate映射现有数据库,并且在尝试填充多对多集合时遇到了问题。数据库本身没有使用外键正确设置,这是我遇到的问题的简化示例。

表:

  1. 用户
  2. 用户组内

实体类:

public class User
{
    public virtual long UserID { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Group> Groups { get; set; }
}
public class Group
{
    public virtual long GroupID { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<User> Users { get; set; }
}
public class UserInGroup
{
    public virtual User User { get; set; }
    public virtual Group Group { get; set; }
    #region Fluent NHibernate Composite Key Overrides
    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;
        var compare = obj as UserInGroup;
        if (compare == null)
            return false;
        return User.UserID == compare.User.UserID &&
               Group.GroupID == compare.Group.GroupID;
    }
    public override int GetHashCode()
    {
        return (User.UserID + "|" + Group.GroupID).GetHashCode();
    }
    #endregion
}

映射类:

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("Users");
        Id(x => x.UserID, "UserID").GeneratedBy.Identity();
        Map(x => x.Name, "Name");
        HasManyToMany(x => x.Groups).Table("UsersInGroups")
                                    .ParentKeyColumn("GroupID")
                                    .ChildKeyColumn("UserID")
                                    .Cascade.All();
    }
}
public class GroupMap : ClassMap<Group>
{
    public GroupMap()
    {
        Table("Groups");
        Id(x => x.GroupID, "GroupID").GeneratedBy.Identity();
        Map(x => x.Name, "Name");
        HasManyToMany(x => x.Users).Table("UsersInGroups")
                                   .ParentKeyColumn("UserID")
                                   .ChildKeyColumn("GroupID")
                                   .Inverse();
    }
}
public class UserInGroupMap : ClassMap<UserInGroup>
{
    public UserInGroupMap()
    {
        Table("UsersInGroups");
        CompositeId().KeyReference(x => x.User, "UserID")
                     .KeyReference(x => x.Group, "GroupID");
    }
}

在我的配置中,我启用了急切加载,HasMany 关系似乎工作正常,但 HasManyToMany 关系返回一个空集合。我已经在集合上尝试了Cascade.All()和Inverse的几种不同组合,但没有成功。任何帮助将不胜感激,谢谢。

在现有数据库上流畅地休眠多对多关系

HasManyToMany(x => x.Users).Table("UsersInGroups")
                           .ParentKeyColumn("UserID")
                           .ChildKeyColumn("GroupID")
                           .Not.LazyLoad();
    HasManyToMany(x => x.Users).Table("UsersInGroups") 
      .ParentKeyColumn("GroupID")
      .ChildKeyColumn("UserID")
      .Not.LazyLoad();