开发者

NHibernate CreateCriteria not working correctly with association and dates

I am trying to create an association to load a list of parent objects based on a child objects date field. I only want parent objects where the date is >= a given date.

The problem is, when I use either today's date or the day before, it returns the correct children. But if I use a date further back in time, like 11-2-2010, it is including children that have a date < 11-2-2010.

Here is the code:

public IList<Parent> GetByDate(string parentId, DateTime date) {
  IList<Parent> list = null;
  using (ISession session = SessionFactory.OpenSession()) {
    list = session.CreateC开发者_运维知识库riteria(typeof(Parent))
                      .Add(Expression.Eq("parent_id", parentId))
                      .CreateCriteria("children")
                        .Add(Expression.Gt("end_date", date)).List<Parent>();
  }
  return list;
} 

and the mapping for Parent:

<id name="id">
  <generator class="native"/>
</id>

<property name="parent_id" />

<bag name="children" lazy="false">
  <key column="parent_id" />
  <one-to-many class="Child" />
</bag>

Thanks in advance!


Adding restrictions to the criteria will not affect what children are loaded, only what parents (which doesn't make sense in your case, because you already have a parentId; use ISession.Get)

If you need to filter the child collection, use ISession.CreateFilter.

Example:

var parent = session.Get<Parent>(parentId);
var children = session.CreateFilter(parent.children, "where end_date > :date")
                      .SetParameter("date", date)
                      .List<Children>();

This assumes the property you're filtering on is called end_date, which doesn't follow .Net naming conventions, but is what you wrote.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜