我正在为两个对象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);
}
但它不起作用,因为我预期它会起作用。可以帮助别人。
答案 0 :(得分: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();
}
}