我如何创建这样的关系?
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(x => x.UserId);
Map(x => x.UserName);
Map(x => x.Password);
Map(x => x.FirstName);
Map(x => x.LastName);
HasManyToMany(x => x.FBFriends).Cascade.All().Table("UserFBFriend");
HasManyToMany(x => x.FBFriends).Cascade.All().Inverse().Table("UserFBFriend");
}
}
public class User : BaseClass<User>
{
public virtual int UserId { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual IList<User> FBFriends { get; set; }
public User()
{
FBFriends = new List<User>();
}
public virtual void AddUserFBFriend(User user)
{
user.FBFriends.Add(this);
FBFriends.Add(user);
}
}
更新
HasManyToMany(x => x.LeftFBFriends).Cascade.All().Table("UserFBFriend");
HasManyToMany(x => x.RightFBFriends).Cascade.All().Inverse().Table("UserFBFriend");
public virtual IList<User> LeftFBFriends { get; set; }
public virtual IList<User> RightFBFriends { get; set; }
public User()
{
LeftFBFriends = new List<User>();
RightFBFriends = new List<User>();
}
答案 0 :(得分:3)
如上所述,我们需要两个集合,分别代表方向A-B,B-A
public virtual IList<User> LeftFBFriends { get; set; }
public virtual IList<User> RightFBFriends { get; set; }
我们需要显式列映射:
HasManyToMany(x => x.LeftFBFriends)
.Table("UserFBFriend")
.ParentKeyColumn("LeftColumn")
.ChildKeyColumn("RightColumn")
.Cascade.All().Table("UserFBFriend");
HasManyToMany(x => x.RightFBFriends)
.Table("UserFBFriend")
.ParentKeyColumn("RightColumn")
.ChildKeyColumn("LeftColumn")
.Cascade.All()
.Inverse()
所以,这样我们就可以正确地指示NHibernate,哪个列将播放父(此ID),哪个列将是子(集合ID)。我们必须为两个集合做到这一点