我有一个名为WorkflowTask的类,它包含一个TaskProperties类属性。使用JoinedSubclassMapping(例如DeliveryTaskProperties)映射的TaskProperties有许多子类。
我需要执行一个NHibernate查询,如下所示,以获取我需要处理的工作流任务列表:
NHibernateSession.Query<WorkflowTask>().Where(x => (x.WorkflowTaskStatus == WorkflowTask.WorkflowTaskStatuses.New && x.TaskProperties.UserAssignedTo=="System")).ToList<WorkflowTask>();
当遍历此列表时,我注意到已识别出TaskProperties的正确子类。但是,当我尝试将wt.TaskProperties转换为DeliveryTaskProperties来访问其数据时,我得到了一个无效的强制转换异常。 我能让它工作的唯一方法是尝试通过指定确切的子类来再次加载任务属性实体:
以下工作,我可以转发到DeliveryTaskProperties类:
wt.TaskProperties = NHibernateSession.Load<DeliveryTaskProperties>(wt.TaskProperties.Id);
立即窗口:
{Workflow.Entities.DeliveryTaskProperties}
[DeliveryTaskPropertiesProxy]:{Workflow.Entities.DeliveryTaskProperties}
base:{Workflow.Entities.DeliveryTaskProperties}
UserAssignedTo:“system”
这不起作用,我得到一个无效的强制转换异常:
wt.TaskProperties = NHibernateSession.Load<TaskProperties>(wt.TaskProperties.Id);
立即窗口:
{Workflow.Entities.DeliveryTaskProperties}
[TaskPropertiesProxy]:{Workflow.Entities.DeliveryTaskProperties}
base:{Workflow.Entities.DeliveryTaskProperties}
UserAssignedTo:“system”
类映射:
public class WorkflowTaskMapping : BaseWorkflowEntityMapping<WorkflowTask>
{
public WorkflowTaskMapping()
{
this.Property(x => x.TaskPropertiesId, map =>
{
map.Column("TaskPropertiesId");
map.Insert(false);
map.Update(false);
map.NotNullable(true);
});
this.ManyToOne<TaskProperties>(x => x.TaskProperties, map =>
{
map.Column("TaskPropertiesId");
map.Cascade(Cascade.All);
map.NotNullable(true);
map.ForeignKey("WFTaskProperties_WFTask_FK");
});
this.Property(x => x.WorkflowTaskStatus, map => map.NotNullable(true));
}
}
public class TaskPropertiesMapping : BaseWorkflowEntityMapping<TaskProperties>
{
public TaskPropertiesMapping()
{
this.Property(x => x.UserAssignedTo, map => map.NotNullable(true));
}
}
public class DeliveryTaskPropertiesMapping : JoinedSubclassMapping<DeliveryTaskProperties>
{
public DeliveryTaskPropertiesMapping()
{
this.Key(x => { x.Column("Id"); x.ForeignKey("DelivTask_TaskProperties_FK"); });
this.Property(x => x.DeliveryAddress, map => map.NotNullable(true));
this.Property(x => x.Deadline, map => map.NotNullable(true));
this.Property(x => x.DeliveryOnDeadline, map => map.NotNullable(true));
}
}
有没有办法在加载WorkflowTask实体时正确加载子类数据,而无需指定确切的子类类型?
答案 0 :(得分:1)
好的,我明白了。虽然我在其他帖子上看到的处理类似问题并不是很清楚,但似乎Eager Fetching为我做了这个伎俩。
如果我更改了我的查询并添加了这样的提取:
NHibernateSession.Query<WorkflowTask>().Where(x => (x.WorkflowTaskStatus == WorkflowTask.WorkflowTaskStatuses.New && x.TaskProperties.UserAssignedTo == "System")).Fetch(x => x.TaskProperties).ToList<WorkflowTask>();
然后nhibernate实际上会在内存中加载子类,尽管类型仍然是基类的类型。这允许稍后转换到子类以访问其属性。
答案 1 :(得分:0)
我不确定这是否是你需要的:
TaskProperties tpAlias = null;
var workflowTasks = NHibernateSession.QueryOver<WorkflowTask>()
.Left.JoinAlias(x => x.TaskProperties, () => tpAlias)
.Where(x => (x.WorkflowTaskStatus == WorkflowTask.WorkflowTaskStatuses.New
&& x.TaskProperties.UserAssignedTo == "System"))
.List();