映射LinqToEntities连接到ViewModel

时间:2012-08-16 13:45:39

标签: valueinjecter

我有以下模型和ViewModel(为简洁起见而编辑):

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

如何将两个表连接并映射到viewmodel?

    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 个答案:

答案 0 :(得分: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);