Search code examples
nhibernatelistentitytransformdto

Populating a DTO with a property list of DTO by using transform


I have a entity called 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; }
}

and a DTO class called Activity:

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

I need to fill DTO from Entity with transform also I want to fill IList<Activity> with the entities which have parentType and parentID. What is the best way to do it, with minimum query?


Solution

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