NHibernate CreateCriteria 无法正确处理关联和日期
我正在尝试创建一个关联来加载基于子对象日期字段的父对象列表。我只想要日期 >= 给定日期的父对象。
问题是,当我使用今天的日期或前一天的日期时,它会返回正确的子项。但如果我使用更早的日期,例如 2010 年 2 月 11 日,则包括日期 << 的儿童。 2010 年 2 月 11 日。
这是代码:
public IList<Parent> GetByDate(string parentId, DateTime date) {
IList<Parent> list = null;
using (ISession session = SessionFactory.OpenSession()) {
list = session.CreateCriteria(typeof(Parent))
.Add(Expression.Eq("parent_id", parentId))
.CreateCriteria("children")
.Add(Expression.Gt("end_date", date)).List<Parent>();
}
return list;
}
以及父级的映射:
<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>
提前致谢!
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.CreateCriteria(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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
向条件添加限制将不会影响加载的子项,只会影响加载的父项(这在您的情况下没有意义,因为您已经有一个parentId;使用
ISession.Get)
如果需要过滤子集合,请使用
ISession.CreateFilter
。示例:
这假设您要过滤的属性称为 end_date,它不遵循 .Net 命名约定,而是您所编写的。
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:
This assumes the property you're filtering on is called end_date, which doesn't follow .Net naming conventions, but is what you wrote.