我想要重写一个与NHibernate交互的模块。商业逻辑变得更加软化,我们决定将我们的linq查询更改为Nhibernate的Criteria。这是旧代码:
nhSession.Query<User>().Where(
u => u.Roles.Contains(query.Role)
)
新代码:
var criteria = nhSession.CreateCriteria<User>("user");
criteria.Add(/* contains? */);
并映射:
<class name="User" table="users">
<id name="Id" column="id">
<generator class="hilo">
<param name="table">hilo</param>
<param name="column">user_id</param>
<param name="max_lo">10</param>
</generator>
</id>
<property name="Password" column="password" />
<bag name="Roles" table="user_roles">
<key column="user_id" />
<element column="role" />
</bag>
</class>
角色是枚举。
如何使用Criteria进行查询的行为与Linq查询类似?
答案 0 :(得分:1)
var criteria = nhSession.CreateCriteria<User>("user");
var roleCriteria = criteria.CreateCriteria("Roles","roles");
roleCriteria.Add(Expression.Eq("role",Role.YourRole);
答案 1 :(得分:1)
假设user_roles
表映射到UserRole
类,并且this question,您可以尝试以下内容:
DetachedCriteria dCriteria = DetachedCriteria.For<UserRole>("ur")
.SetProjection(Projections.Property("ur.UserId"))
.Add(Restrictions.EqProperty("ur.UserId", "user.Id"))
.Add(Restrictions.Eq("ur.Role", query.Role));
var criteria = nhSession.CreateCriteria<User>("user")
.Add(Subqueries.Exists(dCriteria)).List<User>();