Search code examples
c#orchardcms

Why is UserRolesPartRecord not derived from ContentPartRecord in Orchard CMS?


I want to use IContentManager to query some users with the following conditions

  1. published
  2. member of specific role

By using IContentManager.Query(VersionOptions) i can implement condition 1 easily but i can't find a way to implement condition 2 as all other generic extension methods are restricted to record classes derived from ContentPartRecord.

Is there a reason why UserRolesPartRecord not derived from ContentPartRecord thus hindering me from using it in content manager queries?


Solution

  • Because it's old. Last time I had to perform complex queries on users, I had to resort to HQL, not ContentManager.Query. Check out these blog posts: https://weblogs.asp.net/bleroy/querying-orchard-in-hql, https://weblogs.asp.net/bleroy/joining-orchard-part-records-in-hql, https://weblogs.asp.net/bleroy/getting-orchard-content-items-out-of-hql. The end result looks something like this:

    var session = _sessionLocator.For(typeof (UserPartRecord));
    
    const string fromTables =
        "FROM Orchard.ContentManagement.Records.ContentItemVersionRecord ItemVersion"
        + " JOIN ItemVersion.ContentItemRecord Item"
        + " JOIN Item.UserPartRecord User"
        + " WHERE ItemVersion.Published = true"
        + " AND User.UserName IS NOT NULL";
    const whereClause =
        "User.Id NOT IN (SELECT Role.UserId FROM Orchard.Roles.Models.UserRolesPartRecord Role)";
    const orderBy = "ORDER BY User.UserName";
    
    var pageQuery = session.CreateQuery(
        "SELECT DISTINCT User.Id, User.UserName "
        + fromTables
        + " AND " + whereClause
        + " " + orderBy)
        .SetFirstResult(pager.GetStartIndex())
        .SetMaxResults(takeNum);
    
    var ids = pageQuery.List<int>();
    
    var results = contentManager
        .GetMany<UserPart>(ids, VersionOptions.AllVersions, QueryHints.Empty);