我有一个名为ActivityLog的实体:
public class ActivityLog : EntityModel<ActivityLog>
{
public virtual int activityID { get; set; }
public virtual int entityType { get; set; }
public virtual int entityID { get; set; }
public virtual string entityName { get; set; }
public virtual int action { get; set; }
public virtual int parentType { get; set; }
public virtual int parentID { get; set; }
public virtual string parentName { get; set; } }
public virtual string userName { get; set; }
public virtual int instanceID { get; set; }
public virtual DateTime? timeStamp { get; set; }
public virtual DateTime? groupTimeStamp { get; set; }
}
和一个名为Activity的DTO类:
public class Activity
{
public virtual int activityID { get; set; }
public virtual int entityType { get; set; }
public virtual int entityID { get; set; }
public virtual string entityName { get; set; }
public virtual int action { get; set; }
public virtual int parentType { get; set; }
public virtual int parentID { get; set; }
public virtual string parentName { get; set; }
public virtual string userName { get; set; }
public virtual int instanceID { get; set; }
public virtual DateTime? timeStamp { get; set; }
public virtual DateTime? groupTimeStamp { get; set; }
public IList<Activity> activities { get; set; }
}
我需要通过转换来填充实体中的DTO,我还要将IList<Activity>
填入包含parentType
和parentID
的实体。用最少的查询来做最好的方法是什么?
答案 0 :(得分:1)
IList<ActivityLog> activityLogs = ...;
var activities = session.Query<Activity>()
.WhereRestrictionOn(a => a.Parent.Id).IsIn(activityLogs.Select(al => al.parentID))
.WhereRestrictionOn(a => a.Parent.Type).IsIn(activityLogs.Select(al => al.parentType))
.AsEnumerable()
.ToLookUp(a => new { ParentId = a.Parent.Id, ParentType = a.Parent.Type });
var results = activityLogs
.Select(al => new ActivityDTO
{
activityID = al.activityID,
entityType = al.entityType,
...
activities = activities[new { ParentId = al.parentID, ParentType = al.parentType }].ToList()
});
答案 1 :(得分:1)
您可以使用ProjectionList和AliasToBean resulttransformer:
var criteria = session.CreateCriteria <ActivityLog>();
criteria.SetProjection (Projections.ProjectionList()
.Add (Projections.Property ("activityID"), "activityID")
...);
criteria.SetResultTransformer (Transformers.AliasToBean <Activity>());
return criteria.List<Activity>();