0

我正在为两个对象 Employee 和 Department 创建数据模型。Employee 有一个部门列表,Department 有一个员工列表。

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

如何在 Department 类中编写 AddEmployee 方法,在 Employee 类中编写 AddDepartment 方法以使其与 nHibernate 同步?我在Employee类中写了这个

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

     }

但它不像我预期的那样工作。有人可以帮忙。

4

1 回答 1

1

这是我如何处理这些关系的示例:

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

我的User映射如下所示:

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

我的Group映射如下所示:

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();
    }
}
于 2012-04-11T01:49:38.793 回答