就这个问题而言,假设我有一个有多个展品的动物园。每个展览都有自己的时间表和一系列活动,以及负责这些活动的部门和子部门列表。
我有一个相当大的 LINQ 查询,我用它来获取任何附有员工的展品。当使用带有IEnumerable
( session.Query<Exhibit>().AsEnumerable()
) 的查询时,它可以正常工作;但是,当我将查询切换到使用IQueryable
时,NHibernate 会崩溃。
我已将原始错误的初始来源确定为查询中的一个特定条件:
var filtered = session.Query<Exhibit>().Where(x =>
x.AnimalSchedule.Activities
.OfType<FeedActivity>()
.Any(g => g.ResponsibleDepartment.Manager == employee)
);
由于该条件本身很长,因此我继续逐步将其分解:
var collection = session.Query<Exhibit>(); // works
var exhibitAnimalSchedules = collection.Select(x => x.AnimalSchedule); // works
var activities = exhibitAnimalSchedules.SelectMany(x => x.Activities); // could not execute query - Incorrect syntax near the keyword 'from'.
var feedActivities = activities.OfType<FeedActivity>(); // Could not find property nor field 'class' in class 'MyProject.Collections.ScheduleActivityCollection'
var filteredFeedActivities = feedActivities.Where(g => g.ResponsibleDepartment.Manager == employee); // Specified method is not supported.
活动上的错误还给出了 NHibernate 尝试生成的 SQL:
SELECT
FROM [dbo].[Exhibits] exhibit0_
INNER JOIN [dbo].[ExhibitAnimalSchedules] exhibitanima1_ ON exhibit0_.AnimalScheduleID = exhibitanima1_.ScheduleID
INNER JOIN [dbo].[Schedules] exhibitanima1_1_ ON exhibitanima1_.ScheduleID = exhibitanima1_1_.[ID]
WHERE exhibit0_.ZooID IS NULL
如果您注意到,NHibernate 未能列出SELECT
语句中的任何列。
我对这个查询的想法是错误的吗?如果这实际上是 NHibernate 中带有 LINQ lambda 之一的错误,是否有一些解决方法?
更新-请参阅下面的答案
看起来 NHibernate 在确定要加入哪个表以用于.SelectMany(x => x.Activities)
作为参考,以下是所涉及类的所有简化 Fluent 映射:
public class ExhibitMap : ClassMap<Exhibit>
{
public ExhibitMap()
{
References(p => p.AnimalSchedule).Cascade.All();
}
}
public class ScheduleMap : ClassMap<Schedule>
{
public ScheduleMap()
{
Component(x => x.Activities, m => m {
var cfg = m.HasMany<ScheduleActivity>(Reveal.Member<ScheduleActivityCollection>("_innerList")).LazyLoad();
cfg.KeyColumn("ScheduleID").Inverse();
cfg.ForeignKeyConstraintName("FK_Schedule_Activities");
cfg.Cascade.AllDeleteOrphan();
});
}
}
public class ExhibitAnimalScheduleMap : SubclassMap<ExhibitAnimalSchedule>
{
public ExhibitAnimalScheduleMap()
{
References(x => x.Exhibit).Cascade.None();
}
}
public class ScheduleActivityMap : ClassMap<ScheduleActivity>
{
public ScheduleActivityMap()
{
References(x => x.Schedule).Cascade.None().Not.LazyLoad();
}
}
public class FeedActivityMap : SubclassMap<FeedActivity>
{
public FeedActivityMap()
{
this.References(x => x.ResponsibleDepartment).Cascade.All().Not.LazyLoad();
Component(x => x.Departments, m => m {
var cfg = m.HasMany<FeedActivityDepartment>(Reveal.Member<FeedActivityDepartmentCollection>("_innerList")).LazyLoad();
cfg.KeyColumn("ScheduleID").Inverse();
cfg.ForeignKeyConstraintName("FK_Schedule_Activities");
cfg.Cascade.AllDeleteOrphan();
});
}
}