我没有多少VB.net经验,而且我很难搞清楚我做错了什么。我有一个lambda表达式,返回匿名类型的结果集。我试图将此集转换为已知类型并将其返回给调用方法,但我无法将结果集转换为已知类型。或者,也许我以错误的方式解决这个问题。错误是"无法将匿名类型转换为QuickSearchViewModelDataObject类型"。任何帮助将不胜感激。
类别:
Public Class QuickSearchViewModelDataObject
Public Property ItemNum As String
Public Property Description As String
Public Property OnHandQty As Integer?
Public Property PriceClass As String
Public Property Price As Decimal?
Public Property TakeOrderF As Boolean
Public Property Warranty As String
Public Property ActiveF As Boolean
End Class
方法:
Public Function GetItemByItemNumber(itemNumber As String) As QuickSearchViewModelDataObject Implements Model.IInventoryRepository.GetItemByItemNumber
Using context As New MBAModel
Dim returnedItem = context.OneInventories.Join(context.TwoInventories,
Function(mi) mi.ItemNum,
Function(im) im.ItemNum,
Function(mi, im) New With {mi, im}) _
.Select(Function(o) New With
{
.Description = o.mi.Description, _
.OnHandQty = o.im.OnHandQty, _
.PriceClass = o.mi.Class, _
.Warranty = o.mi.Warranty, _
.Price = o.im.Price, _
.TakeOrderF = o.mi.TakeOrderF, _
.ItemNum = o.mi.ItemNum, _
.ActiveF = o.mi.ActiveF
}).Where(Function(x) x.ItemNum = itemNumber AndAlso x.ActiveF).FirstOrDefault()
Return returnedItem
End Using
End Function
答案 0 :(得分:3)
您不需要Select子句,只需要Where子句,这将返回实体类型。
.Where(Function(x) x.ItemNum = itemNumber AndAlso x.ActiveF).FirstOrDefault()
答案 1 :(得分:1)
修改:OneFineDay是正确的 - 您可以从加入获得QuickSearchViewModelDataObject
权限;不需要选择。关于Join的第三个参数:
Function(mi, im) New QuickSearchViewModelDataObject() With {
.Description = mi.Description, _
...
})
...
这就是你需要在最后获得正确的对象类型。 请参阅小提琴:here
我会先回答我之前的答案,以防其他人帮忙:
如果您一直在处理IEnumerable(Of QuickSearchViewModelDataObject)
,则不需要使用Select进行投影。但是,如果您正在处理匿名类型(例如,来自较早的Join
),并且您需要投射到最终所需的类型,那么这很简单:
.Select(Function(o) New QuickSearchViewModelDataObject() With {
.Description = o.mi.Description, _
.OnHandQty = o.im.OnHandQty, _
.PriceClass = o.mi.Class, _
.Warranty = o.mi.Warranty, _
.Price = o.im.Price, _
.TakeOrderF = o.mi.TakeOrderF, _
.ItemNum = o.mi.ItemNum, _
.ActiveF = o.mi.ActiveF
})
在这种情况下,选择之前LINQ查询的形状并不重要 - 你肯定会从中获得QuickSearchViewModelDataObject
。 (如果您想要投影到DTO而不是实体对象,这也很有用。)