本文介绍了如何保持多对多关系与nhibernate同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

这是我处理这些关系的一个示例:

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

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

这篇关于如何保持多对多关系与nhibernate同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 00:35