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

后端 未结 2 1759
误落风尘
误落风尘 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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();
    

    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

提交回复
热议问题