代码之家  ›  专栏  ›  技术社区  ›  stiank81

运行NHibernate查询而不加入

  •  3
  • stiank81  · 技术社区  · 16 年前

    我有一个流畅的映射,它将一个虚构的类Customer映射到一个订单列表。现在我想从数据库中获取所有客户而不加载订单。这可以在query/criteria/etc中指定,还是LazyLoading是唯一的解决方案?

    虚构类:

    public class Customer
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual IList<Order> Orders { get; set; }
    }
    
    public class Order
    {
        public virtual int Id { get; set; }
        // ++ 
    }
    
    2 回复  |  直到 16 年前
        1
  •  2
  •   Owen Pauling tmatuschek    10 年前

    不管怎样,延迟加载都会自动完成,您是否在尝试避免延迟加载?为什么?

    IList<Customer> customers = _session.CreateCriteria<Customer>().List<Customer>();
    

    只会给你所有的顾客。只有在调用客户实体上的订单集合时,才会从数据库中提取订单,例如:

    foreach(Customer customer in customers)
    {
        IList<Order> orders = customer.Orders; // Will hit the database
    }
    


    更新: 对评论的回应。如果通过web服务发送POCO,您应该考虑使用报表查询,因为POCO会丢失对NHibernate会话对象的附件,因此延迟加载将不起作用(Orders collection将只返回NULL)。换句话说,正确调用web服务的“thing”不会了解任何有关NHibernate或域模型的信息,因此:

    public IList<CustomerView> GetAllCustomers()
    {
        return (from c in _session.Query<Customer>()
                select new CustomerView()
                {
                    Id = c.Id,
                    Name = c.Name
                }).ToList();
    }
    
    public CustomerDetail GetCustomerFromId(int id)
    {
        return (from c in _session.Query<Customer>()
                where c.Id == id
                select new CustomerDetail()
                {
                    Id = c.Id,
                    Name = c.Name
                    FullAddress = c.FormatFullAddress(),
                    Orders = c.Orders,
                    // other properties (snip)
                }).SingleOrDefault();
    }
    

    http://nhibernate.info/doc/nh/en/index.html#querycriteria-projection

        2
  •  1
  •   Frederik Gheysels    16 年前

    您可以在条件中指定FetchMode:

    var crit = session.CreateCriteria (typeof(SomeObject));
    crit.SetFetchMode ("association", FetchMode.Eager);