如何转换为具有集合的强类型?

时间:2013-03-01 15:56:38

标签: .net vb.net linq casting

我正在尝试将包含某些集合的实体转换为Model,但我无法弄清楚如何将集合包含在模型中。

仅举一个简单的例子,请参阅下面的模型:

Namespace Models

    Public Class ProductModel
        Public Property ID As Integer
        Public Property Description As String
        Public Property IsInStock as Boolean
        Public Property Orders As List(Of ProductOrderModel)

    End Class

    Public Class ProductOrderModel
        Public Property ID As Integer
        Public Property OrderDate As DateTime
        Public Property DeliveredDate As DateTime?
        Public Property ShippingAddress As String
    End Class

End Namespace

现在我可以轻松地进入下面显示的产品模型:

Dim simplifiedProductModel as ProductModel =
    From p in dc.Products _
    Select New ProductModel With { _
        .ID = p.ProductID, _
        .Description = p.ProductDescription, _
        .IsInStock = p.ProductIsInStock, _
        .OrderCount = p.Orders.Count() _
        }

我无法弄清楚如何使用其简化模型来包含该集合。

Dim simplifiedProductModel as ProductModel =
    From p in dc.Products _
    Select New ProductModel With { _
    .ID = p.ProductID, _
    .Description = p.ProductDescription, _
    .IsInStock = p.ProductIsInStock, _
    .OrderCount = p.Orders.Count(), _
    .Orders = p.orders.???? ===> New ProductOrderModel 
        With { 
            .ID = ???? o.OrderID , 
            .OrderDate = ???? o.Createdate, 
            etc.  
            }

2 个答案:

答案 0 :(得分:1)

喜欢这个吗?

Dim simplifiedProductModel as ProductModel = From p in dc.Products _
                                        Select New ProductModel With { _
                                        .ID = p.ProductID, _
                                        .Description = p.ProductDescription, _
                                        .IsInStock = p.ProductIsInStock, _
                                        .OrderCount = p.Orders.Count(), _
                                        .Orders = p.orders.Select( _
                                            Function(o) New ProductOrderModel _
                                                With { _
                                                    .ID = o.OrderID , _
                                                    .OrderDate = o.Createdate, _
                                                    etc.  
                                                }
                                            )
                                         }

答案 1 :(得分:0)

首先,您必须将Public Property Orders As String As List(Of ProductOrderModel)声明修改为Public Property Orders As List(Of ProductOrderModel)。 然后你可以使用这个

.Orders = (from order in p.orders
              Select New ProductOrderModel 
                     With { 
                             .ID = order .OrderID , 
                             .OrderDate = order.Createdate, 
                                  etc.
                          }).ToList()