与nhibernate的双向关系模式

Ber*_*ryl 2 nhibernate domain-driven-design fluent-nhibernate

在我的域中,员工和部门具有一对多的双向关系; 为了让子Employee同步这个,我有一个'内部'访问字段,用于部门中的Employees的Set(Iesi for NHibernate),否则将只读公开.像这样:

系类:

protected internal ISet<Employee> _staff;  
public virtual ReadOnlyCollection<Employee> Staff {  
   get { return new List<Employee>(_staff).AsReadOnly(); }   
}  
public virtual void AddStaff(Employee emp) {
    emp.Department = this;  } 
}
Run Code Online (Sandbox Code Playgroud)

员工类:

private Department _department;
public virtual Department Department {
   set {
       // check valid value, etc.
       value._staff.Add(this);
   }
}
Run Code Online (Sandbox Code Playgroud)

我在我的(FNH)映射AsField(Prefix.Underscore)中进行访问,但由于我无法使Department._staff字段虚拟NH不满意.我想我可以使该字段成为虚拟属性并强制提供它,但这感觉就像我让域类过分意识到持久性.

我正在学习NH和FNH,我知道我需要一个很好的关系映射入门,但我对这篇文章的主要问题是我的域类中的逻辑:
1)这是一个很好的c#编程模式,用于一个只读集合双向关系?
2)使NHibernate更有用的最佳方法是什么?

感谢分享!
Berryl

Jam*_*Ide 11

我使用这种模式实现一对多关系:

public class Department
{
    private IList<Employee> _staff = new List<Staff>();

    public virtual IEnumerable<Employee> Staff
    {
        get { return _staff; }
    }

    // Add and Remove have additional checks in them as needed

    public virtual void AddStaff(Employee staff)
    {
        staff.Department = this;
        _staff.Add(staff);
    }

    public virtual void RemoveStaff(Employee staff)
    {
        staff.Department = null;
        _staff.Remove(staff);
    }
}
Run Code Online (Sandbox Code Playgroud)

 

public class Employee
{
    public virtual Department Department { get; internal set; }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,部门是这种关系的反面.