0

我正在爲Employee和Department兩個對象創建數據模型。員工有一個部門清單,部門有一個員工清單。如何保持與nhibernate同步的多對多關係?

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

    } 

寫這篇但正如我預料到work.Can別人幫助它不工作。

+0

我已經發布了一個關於我如何處理這些場景的例子,但爲什麼你的代碼不工作預期?你在期待什麼? – 2012-04-11 01:51:25

+0

當我試圖保存這個像db.session.Save(Employee)時會導致循環依賴;它歸屬於有部門的員工,部門內部有員工等。這是循環的。我不確定這是否正確。如果我錯了,有人能糾正我嗎? – 8GB 2012-04-11 13:58:22

回答

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

我這樣做的方式完全相同,至少可以將樣板代碼與應用程序代碼分開,併爲您提供單點故障。您甚至可以將便利方法(添加,刪除)添加到組類以刪除用戶。 – 2012-04-16 09:04:05

+0

@ SebastianEdelmeier,那個類有一些方法可以做到這一點。在上面的代碼中,add和remove都會調用'Group'中的那些方法。 – 2012-04-16 11:32:56