2011-11-24 67 views
1

我有一個名爲ActivityLog實體:通過變換填充一個DTO與DTO的屬性列表

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; } 
} 

和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>與實體有parentTypeparentID。用最少的查詢來完成它的最佳方式是什麼?

+0

[AutoMapper(http://automapper.org/) –

回答

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() 
    }); 
+0

感謝會救我使用automapper。 – iboware

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>(); 
+0

我已經嘗試過這種方法,但它不適用於'IList 活動'@ Firo的答案看起來更合適。謝謝你的回答。 – iboware