2012-08-16 156 views
0

我有以下型號和的ViewModels(編輯爲了簡潔):映射LinqToEntities加入到視圖模型

 Order Model: 
      OrderId 
      ShippingAddressId 
      ..... 
    Address Model: 
      AddressId 
      ..... 
    OrderViewModel: 
      Some Property from Order Model and Address Model 

如何內部聯接兩個表,並映射到一個視圖模型?

var query= from o in ctx.Orders 
     join addr in ctx.Addresses 
     on o.ShippingAddressId equals addr.AddressId 
     select new OrderViewModel.InjectFrom(o) 
           .InjectFrom(addr) 
           as OrderViewModel; 

此代碼無效。

回答

1

首先,您需要兌現與ToList結果:

var query = (from o in ctx.Orders 
      join addr in ctx.Addresses 
      on o.ShippingAddressId equals addr.AddressId 
      select new { o, addr } 
      ).ToList() 
      .Select(x => new OrderViewModel().InjectFrom(x.o) 
               .InjectFrom(x.addr) 
          as OrderViewModel);