我正在使用 Fluent NHibernate 映射现有数据库,并且在尝试填充多对多集合时遇到了问题。数据库本身没有使用外键正确设置,这是我遇到的问题的简化示例。
表:
- 用户
- 团体
- 组内用户
实体类:
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 的几种不同组合,但均未成功。任何帮助将不胜感激,谢谢。