how to keep many to many relationships in sync with nhibernate?

独自空忆成欢 提交于 2019-12-11 14:36:54

问题


I am creating data model for two objects Employee and Department. Employee has a list of departments and Department has a list of employees.

    class Employee{
             private IList<Department> _departments;
       public Employee()
       {
          _departments = new List<Department>();
       }
       public virtual ReadOnlyCollection<Department> Departments{
          get {return new ReadOnlyCollection<Department>(_departments);}
       }
     }

    class Department{
             private IList<Employee> _employees;
       public Department()
       {
          _departments = new List<Employee>();
       }
       public virtual ReadOnlyCollection<Employee> Employees{
          get {return new ReadOnlyCollection<Employee>(_employees);}
       }
     }

How do I write AddEmployee method in Department class and AddDepartment method in Employee class to make it in sync with nHibernate? I wrote this in Employee class

     public virtual void AddDepartment(Department department)
     {
        if (!department.Employees.Contains(this))
        {
            department.Employees.Add(this);
        }
        _departments.Add(department);

     }

But it doesnt work as I expected it to work.Can someone help.


回答1:


This is an example of how I handle these relationships:

public class User
{
    private IList<Group> groups;
    public virtual IEnumerable<Group> Groups { get { return groups.Select(x => x); } }

    public virtual void AddGroup(Group group)
    {
        if (this.groups.Contains(group))
            return;

        this.groups.Add(group);
        group.AddUser(this);
    }

    public virtual void RemoveGroup(Group group)
    {
        if (!this.groups.Contains(group))
            return;

        this.groups.Remove(group);
        group.RemoveUser(this);
    }
}

My User mapping looks like this:

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        //Id, Table etc have been omitted

        HasManyToMany(x => x.Groups)
            .Table("USER_GROUP_COMPOSITE")
            .ParentKeyColumn("USER_ID")
            .ChildKeyColumn("GROUP_ID")
            .Access.CamelCaseField()
            .Cascade.SaveUpdate()
            .Inverse()
            .FetchType.Join();
    }
 }

My Group mapping looks like this:

public class GroupMap : ClassMap<Group>
{
    public GroupMap()
    {
        //Id, Table etc have been omitted

        HasManyToMany(x => x.Users)
            .Table("USER_GROUP_COMPOSITE")
            .ParentKeyColumn("GROUP_ID")
            .ChildKeyColumn("USER_ID")
            .Access.CamelCaseField();
    }
}


来源:https://stackoverflow.com/questions/10090918/how-to-keep-many-to-many-relationships-in-sync-with-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!