简体   繁体   English

如何使用带有NHibernate的条件Api将子查询写为别名

[英]How to to write subqueries as aliases using the Criteria Api with NHibernate

hey guys, say I have Entities and mappings like this: 大家好,说我有这样的实体和映射:

public class Episode
{
    Guid Id {get;set;}
    String Title {get;set;}
    List<Group> Groups {get;set;}
}

public class Group
{
    Guid Id {get;set;}
    DateTime PubDate {get;set;}
}

public class EpisodeMap : ClassMap<Episode>
{
    public EpisodeMap()
    {
        //other mappings..
        Map.HasMany(ep => ep.Groups);
    }
}

So, basically, an Episode has many Groups. 因此,基本上,一个情节有很多组。 Each Group has a PubDate, and so an Episode has many PubDates. 每个组都有一个发布日期,因此一个情节有许多发布日期。

I'm trying to write a query using the NHibernate Criteria API which lets me query Episodes and Order them by PubDate given that I have a Group Id. 我正在尝试使用NHibernate Criteria API编写查询,考虑到我具有组ID,该查询可让我查询剧集并按PubDate对其进行排序。

Essentially, how do I write the equivalent Criteria API query for this SQL query: 本质上,如何为该SQL查询编写等效的Criteria API查询:

Select 
    e.*, 
    (Select top 1 ReleaseDate From EpisodeGroups where EpisodeFk = e.Id and GroupFk = @GroupId) as myPubDate 
From Episodes e 
Order By myPubDate

Please help! 请帮忙! cheers guys 欢呼的家伙

public DetachedCriteria BuildCriteria(int episodeId, int groupId)
{

    var groupCriteria = DetachedCriteria.For<Groups>()
        .Add(Restrictions.Eq("this.Id", groupId))
        .Add(Restrictions.Eq("Group.Id", groupId)) 
        .AddOrder(Order.Asc("Group.PubDate"));

    return DetachedCriteria.For<EpisodeGroups>()
               .Add(Restrictions.Eq("this.Id", episodeId))
               .Add(Subqueries.PropertyIn("this.Groups", groupCriteria)
               .SetMaxResult(1);
}

Then you can do something like this... 然后你可以做这样的事情...

var episodes = _repository.ExectueCriteria<EpisodeGroups>(BuildCriteria(episodeId, groupId))

Just as a special consideration, the reason why you would want to eagerly load the Group entity is in case you would like to use LINQ to compare the PUBDATE later on in your business logic as opposed to using a strict detached criteria. 出于特殊考虑,您希望热切加载Group实体的原因是为了防止您以后在业务逻辑中使用LINQ比较PUBDATE而不是使用严格的分离标准。

We have found that by eagerly loading the attributes of an entity will reduce the total number of calls to our database. 我们发现,通过热切加载实体的属性将减少对我们数据库的调用总数。

No guarantees this code works... but it should at least get you started, good luck :) 不能保证此代码能正常工作...但是至少应该可以帮助您入门,祝您好运:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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