nhibernate - Create child by updating parent, or create explicitly?

前端 未结 1 1804
予麋鹿
予麋鹿 2020-12-11 12:44

What is the preferred method for creating children objects?

  1. Adding the child to a collection on it\'s parent and calling update on the parent, or
  2. Crea
1条回答
  •  执笔经年
    2020-12-11 13:26

    Not sure what would be the "preferred method" (it could depend on who does prefer). But I can share my way

    If the parent is a root entity, then we should save all the reference tree in in one shot: session.SaveOrUpdate(parent).

    E.g. Employee has collection of Educations. In such case, it should go like this

    1. create Education give it reference to employee,
    2. Add() it to collection employee.Educations.
    3. Have/make the mapping inverse, cascade="all-delete-orphan" ...
    4. NHibernate will do what we expect on session.SaveOrUpdate(parent)

    Some snippets in xml:

    
    
      
      
    
      
        
        
      
      ...
    

    And the Education

    
      
    
      
    ...
    

    in fluent:

    public class EmployeeMap : ClassMap
    {
      public EmployeeMap()
      {
          BatchSize(25)
          ...
          HasMany(x => x.Educations)
            .AsBag()
            .BatchSize(25)
            .LazyLoad() 
            .Cascade.AllDeleteOrphan() 
            .Inverse()
            .KeyColumn("Employee_ID")
    
    public class EducationMap : ClassMap
    {
      public EducationMap()
      {
         ...
         References(x => x.Employee, "Employee_ID")
              .Not.Nullable()
              ...
    

    And now the C# relations:

    // business
    var employee = ...;
    var education = new Education
    {
       Employee = employee, 
       ...
    };
    employee.Educations.Add(education);
    
    // DAO
    session.SaveOrUpdate(employee);
    

    If the parent is not root, there is just a relation (Employee has collection of Subordinates of type Employee), keep the persisting separated

    0 讨论(0)
提交回复
热议问题