如何将类的集合分配给新的viewmodel

时间:2014-07-12 12:20:46

标签: c# asp.net-mvc linq

我有这种情况:

我想使用我只想要的属性制作ViewModel,但我的问题是Collections。所以这是一个例子:

主要课程:

public class Customer
{
  public int Id { get; set; }
  public string Name { get; set; }

  public virtual ICollection<Order> Orders { get; set; }
  // remove some code for brevity
}

public class Order
{
  public int Id { get; set; }
  public string ItemName { get; set; }
  public int CustomerId { get; set; }

  public virtual Customer Customer { get; set; }
  // remove some code for brevity.
}

查看模特:

public class OrderVM
{
  public string ItemName { get; set; }
}

public class CustomerVM
{
  public string Name { get; set; }
  public ICollection<OrderVM> Orders { get; set; }
}

然后我尝试了这样的事情:

_customerService.Include(c => c.Orders)
  .Select(x => new CustomerVM
                   {
                     Name = x.Name,
                     Orders = x.Orders.Select(order => new OrderVM { ItemName = order.ItemName }) // but it says cannot convert implicitly from IEnumerable to ICollection
                   }
)

简而言之,我如何填充CustomerVM的属性?我只想选择我想要的。有什么想法吗?真的卡在这里。

2 个答案:

答案 0 :(得分:1)

只需使用ToList()将IEnumerable转换为ICollection。未经测试但应该可以使用

customerService.Include(c => c.Orders)
.Select(x => new CustomerVM
               {
                 Name = x.Name,
                 Orders = x.Orders.Select(order => new OrderVM { ItemName = order.ItemName }).ToList() 
               }

答案 1 :(得分:1)

Linq .Select()生成IEnumerable<T>,但您的媒体资源为ICollection<T>。您可以在查询中附加.ToList()以生成List<T> ICollection<T>

customerService.Include(c => c.Orders)
  .Select(x => new CustomerVM
  {
    Name = x.Name,
    Orders = x.Orders
      .Select(order => new OrderVM { ItemName = order.ItemName }).ToList() 
  }

或者,如果您并不特别需要OrdersICollection,那么您可以将属性定义更改为

public IEnumerable<OrderVM> Orders { get; set; }