嗨,我在 Nhibernate 中遇到映射问题。当我运行引用我的实体的组件类之一的 linq 查询时,我得到一个 QueryException,如下所示:
我有一张记录表,我想将这些记录映射到标题实体的多个对象中。
问题:
我的 Headline
实体被分成多个逻辑类,如下所示
public class Headline:Entity
{
public virtual DateTime Date { get; set; }
public virtual TeamTarget Teamtarget { get; set; }
}
public class TeamTarget : Entity
{
public virtual DateTime FromDate { get; set; }
public virtual DateTime ToDate { get; set; }
public virtual TargetItem AchievedTarget { get; set; }
public virtual Team Team { get; set; }
}
public class TargetItem : Entity
{
public virtual decimal ClosedCases { get; set; }
public virtual decimal Invoicing { get; set; }
}
映射文件:
public class HeadlineMap: ClassMap<Headline>
{
public HeadlineMap()
{
Table("Headlines.Headlines");
Id(x => x.Id).Column("HeadlinesId");
Map(x => x.Date);
Component(x => x.Teamtarget, t =>
{
t.References(x => x.Team).Column("TeamId").Cascade.None();
t.Component(x => x.AchievedTarget, ti =>
{
ti.Map(x => x.Invoicing).Column("TeamInvoicing");
ti.Map(x => x.ClosedCases).Column("TeamClosedCases");
});
});
我正在运行的 Linq 查询如下所示:
decimal closedCases = _headlineRepository.All
.Where(x =>
x.Date >= DateTimeExtensionMethods.FirstDayOfMonthFromDateTime(selectMonthFromDate)
&& x.Date <= DateTimeExtensionMethods.LastDayOfMonthFromDateTime(selectMonthFromDate)
&& x.Teamtarget.Team.Id == teamId
).Average(x => x.Teamtarget.AchievedTarget.ClosedCases);
我知道我可以通过团队 id 使用团队实体来访问标题项目,这有效,只是在实现目标的映射方面有问题。
有任何想法吗?
最佳答案
我认为你的映射很好。但据我所知,不可能使用 Linq to NHibernate 查询嵌套组件。它无法理解join要做什么,变得太复杂了。
我认为可以使用 NHibernate 3 的 QueryOver API 使用 JoinQueryOver 或 JoinAlias。你应该阅读这个:QueryOver in NH 3.0
也许这样的事情会起作用:
Headline headlineAlias = null;
TeamTarget targetAlias = null;
Team teamAlias = null;
TargetItem targetItemAlias = null;
var query = session.QueryOver<Headline>(() => headlineAlias)
.JoinAlias(() => headlineAlias.Teamtarget, () => targetAlias)
.JoinAlias(() => targetAlias.Team, () => teamAlias)
.JoinAlias(() => targetAlias.AchievedTarget, () => targetItemAlias)
.Where(x => x.Date >= DateTimeExtensionMethods.FirstDayOfMonthFromDateTime(selectMonthFromDate) && x.Date <= DateTimeExtensionMethods.LastDayOfMonthFromDateTime(selectMonthFromDate))
.And(() => teamAlias.Id == teamId)
.Select(Projections.Avg(() => targetItemAlias.ClosedCases))
.SingleOrDefault<decimal>();
关于fluent-nhibernate - FluentNHibernate : Nested component mapping results in NHiberate QueryException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6776889/