简体   繁体   中英

How to convert linq query to Nhibernate's Criteria?

I am tying to rewrite a module which interacts with NHibernate. The buisness logic becomes more sofisticated and we decided to change our linq queries to Nhibernate's Criteria. Here is the old code:

nhSession.Query<User>().Where(
    u => u.Roles.Contains(query.Role)
)

And the new code:

var criteria = nhSession.CreateCriteria<User>("user");
criteria.Add(/* contains? */);

And mapping:

<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>

Where Roles is an enum.

How to make the query with Criteria behave like the Linq query?

var criteria = nhSession.CreateCriteria<User>("user");
var roleCriteria = criteria.CreateCriteria("Roles","roles");
roleCriteria.Add(Expression.Eq("role",Role.YourRole);

Assuming the user_roles table is mapped to a UserRole Class, and from this question , you may try something like :

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM