如何使用 Criteria Api 和 NHibernate 将子查询编写为别名
嘿伙计们,假设我有这样的实体和映射:
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);
}
}
所以,基本上,一个剧集有很多组。每个组都有一个 PubDate,因此一个剧集有多个 PubDate。
我正在尝试使用 NHibernate Criteria API 编写一个查询,它允许我查询剧集并按 PubDate 排序,因为我有一个组 ID。
本质上,我如何为此 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
请帮忙!干杯,伙计们
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.
Essentially, how do I write the equivalent Criteria API query for this SQL query:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
然后你可以做这样的事情...
作为一个特殊的考虑,你想要急切地加载 Group 实体的原因是为了防止你想在你的业务逻辑中使用 LINQ 来比较 PUBDATE,而不是使用严格的独立标准。
我们发现,通过急切加载实体的属性将减少对数据库的调用总数。
不能保证此代码有效...但它至少应该让您开始,祝你好运:)
Then you can do something like this...
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.
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 :)