R – NHibernate one way, one-to-many, mapping question

nhibernateone-to-many

I have a scenario in NHibernate where I have a one-to-many relationship between entities Employee and EmployeeStatus.

Employee has properties eg: ID, Name and an IList of EmployeeStatus, whilst EmployeeStatus, for the purposes of this question, just has it's own ID and some free text.

I don't need to hold a reference to Employee from EmployeeStatus, the management of status' will be done purely through the Employee entity – adding to the IList property. IE: I want to quite simply be able to do the following;

Employee e = new Employee();
e.Name = "Tony";
e.StatusList.Add( new EmployeeStatus("Status A") );
e.StatusList.Add( new EmployeeStatus("Status B") );
session.Save(e);

I've tried various methods, including creating a one way one-to-many mapping where inverse is false, cascade set to all-delete-orphan, which all looks like it should work, but it generates an exception about being unable to set the EmployeeId in EmployeeStatus. I'm led to believe that this is because NHibernate wants to do an insert with EmployeeId as NULL and then update it to the ID of the parent.

I guess I'm missing something here, so quite simply – can anyone tell me what my mapping file should look like to achieve the above?

Thanks in advance

Tony

— edit: Heres a rough idea of the classes as requested —

public class Employee
{
  private IList<EmployeeStatus> _statusList;

  public Employee()
  {
    _statusList = new List<EmployeeStatus>();
  }

  public virtual int Id{ get; set; }

  public virtual string Name{ get; set; }

  public virtual IList<EmployeeStatus> StatusList
  {
    get
    {
      return _statusList;
    }
  }
}

public class EmployeeStatus
{
  public virtual int Id{ get; set; }
  public virtual string StatusText{ get; set; }

  public EmployeeStatus()
  {
  }

  public EmployeeStatus(string statusText)
  {
    StatusText = statusText;
  }
}

Best Answer

The scenario you've described is just a basic one-to-many mapping. Here is the Fluent NHibernate mapping for this:

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap()
    {
        WithTable("Employee");
        HasMany(employee => employee.StatusList)
        .Cascade.All();
    }
}

You do not need to maintain a reference from EmployeeStatus back to Employee to achieve this.

Related Topic