在同一张桌子上流利的NHibernate多对多

时间:2014-09-14 13:36:27

标签: c# nhibernate fluent-nhibernate

我如何创建这样的关系?

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>();
    }

1 个答案:

答案 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)。我们必须为两个集合做到这一点