1

假设我有一个带有一些字段的实体和一个像这样的集合

Entity
int Id {get; set;}
string Name {get; set;}
string Title {get; set;}
List<Order>Orders {get; set;}

Order
int Id {get; set;}
string Name {get; set;}
Entity Entity {get; set;}

现在我想创建 EntityOrderViewModel,它只代表两个实体的几个属性。像这样

EntityOrderViewModel
int Id {get; set;}
string EntityName {get; set;}
string EntityTitle {get; set;}
string OrderName {get; set;}
int OrderId {get; set;}

EntityOrderViewModel(Entity x)
{
   Id = 1; 
   EntityName = x.Name; 
   EntityTitle = x.Title;
   foreach(Order order in x.Orders)
   {
      OrderName = order.Name;
   }
}

public static List<EntityOrderViewModel> FromMyDomain(IList<Entity> x)
{
    List<EntityOrderViewModel> vm= new List<EntityOrderViewModel>();

    foreach (Entity e in x)
    {
        vm.Add(new EntityOrderViewModel(e));
    }
    return vm;
}

现在从我的控制器我想调用所有这样的实体

//opensession
   // open transaction
      List<Entity> data = session.Query<Entity>().ToList();
   //end transaction
      transaction.commit();
//end session      
      return EntityOrderViewModel.FromMyDomain(data);
4

1 回答 1

0

既然你在控制器中有你的会话,为什么不直接水合视图模型呢?

from entity in session.Query<Entity>()
join order in session.Query<Order> join entity.EntityId on order.Entity.EntityId
select new EntityOrderDTO // or anon 
{
  EntityId = entity.EntityId,
  Name = entity.Name,
  OrderName = order.OrderName
}

加入会照顾你的 n+1

于 2012-05-29T07:39:35.030 回答