nhibernate - disable automatic\lazy loading of child records for one to many relationsihps

后端 未结 2 1758
误落风尘
误落风尘 2021-02-08 11:38

I would like to know if there is a way to disable automatic loading of child records in nHibernate ( for one:many relationships ).

We can easily switch off lazy loading

相关标签:
2条回答
  • 2021-02-08 12:07

    Given your request, you could simply not map from Department to Employees, nor have an Employees property on your department. This would mean you always have to make a database hit to find the employees of a database.

    Aplogies if these code examples don't work out of the box, I'm not near a compiler at the moment

    So, your department class might look like:

     public class Department 
     { 
         public int Id { get; protected set; }
         public string Name { get; set; }
         /* Equality and GetHashCode here */
     }
    

    and your Employee would look like:

     public class Employee
     { 
         public int Id { get; protected set; }
         public Name Name { get; set; }
         public Department Department { get; set; }
         /* Equality and GetHashCode here */
     }
    

    Any time you wanted to find Employees for a department, you've have to call:

    /*...*/
    session.CreateCriteria(typeof(Employee))
        .Add(Restrictions.Eq("Department", department)
        .List<Employee>();
    

    Simply because your spec says "Departments have many Employees", doesn't mean you have to map it as a bi-directional association. If you can keep your associated uni-directional, you can really get your data-access to fly too.

    Google "Domain Driven Design" Aggregate, or see Page 125 of Eric Evan's book on Domain Driven Design for more information

    0 讨论(0)
  • 2021-02-08 12:11

    You can have the lazy attribute on the collection. In your example, Department has n employees, if lazy is enabled, the employees will not be loaded by default when you load a department : http://www.nhforge.org/doc/nh/en/#collections-lazy

    You can have queries that explicitly load department AND employees together. It's the "fetch" option : http://www.nhforge.org/doc/nh/en/#performance-fetching-lazy

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