优化nhibernate查询

时间:2012-01-03 22:28:01

标签: c# nhibernate session optimization

我有以下关系

    class Author
    {
       int Id;
    }

    class Publisher
    {
       int Id;
    }

    class Book
    {
       Publisher Publisher;
       Author Author;
       DateTime PublishDate;
    }

我想优化以下查询:

    foreach (Publisher)
    {
       foreach (Author)
       {
          session.Query<Book>()
             .Where(x=> x.Author.Id == Author.Id && x.Publisher.Id ==Publisher.Id)
             .OrderByDescending(x=> x.PublishDate)
             .Take(5);
       }
    }

我意识到这个代码性能明显可怕,我怎样才能改进它并在更少的查询中获得相同的结果?

非常感谢!

1 个答案:

答案 0 :(得分:0)

我们有很多方法可以做。这取决于你的用例,你先得到哪个对象

这里我提到了一种方式

DetachedCriteria forBook=DetachedCriteria.For<Book>();
forBook.CreateCriteria("Publisher");
forBook.CreateCriteria("Author");
ICriteria executableCriteria=forBook.GetExecutableCriteria(session);
executableCriteria.SetFirstResult(0).SetMaxResult(5);
executableCriteria.AddOrder(Order.Desc("PublishDate"));
executableCriteria.List<Book>();