标准+ nhibernate +基于2个id的retrive对象

时间:2012-02-19 19:09:18

标签: nhibernate criteria

我想基于2个id来检索一个对象。

这是正确的标准吗?

var notes = session
                .CreateCriteria(typeof(Note))
                .Add(Restrictions.Eq("Product", productId))
                .Add(Restrictions.Eq("User", userId))
                .List<Note>();

此查询是否会获取属于用户和产品的备注?

并执行此标准:

var comments = session
                .CreateCriteria(typeof(Comment))
                .Add(Restrictions.Eq("Product", productId))
                .Add(Restrictions.Eq("IsOwnComment", 0))
                .List<Comment>();
            return comments;

返回布尔值为0的产品的注释?

我做对了吗?

BR

2 个答案:

答案 0 :(得分:2)

var notes = session
                .CreateCriteria(typeof(Note))
                .Add(Restrictions.Eq("Product", productId))
                .Add(Restrictions.Eq("User", userId))
                .List<Note>();

这不会像这样工作。您需要提供产品和用户的关联路径的完整实体。你可以做的是使用特殊的id属性:

var notes = session
                .CreateCriteria(typeof(Note))
                .Add(Restrictions.Eq("Product.id", productId))
                .Add(Restrictions.Eq("User.id", userId))
                .List<Note>();

对于第二个示例,请使用Restrictions.IsNull("IsOwnComment")

答案 1 :(得分:1)

当您使用添加Criteria的表达式而不识别它们之间的And或Or表达式时,NHibernate将默认使用And,因此您编写的critera将与这些HQL查询相同:

"from Note note where note.Product=:productId and note.User=:userId"

"from Comment comment where comment.Product=:productId and comment.IsOwnComment=0"

只有一点需要注意:如果产品和用户是多对一关系,这些查询将无效,您应该使用Product.Id和User.Id作为属性名称

相关问题