0

我有以下情况: ADoctor可以有多个Companions. 一个Companion也可以有多个Doctors。这是我的课程(减去上下文):

Public Class Doctor

    Public Property DoctorId As Integer
    Public Property Regeration As Integer
    Public Property Name As String
    Public Property Actor As String
    Public Property Companions As List(Of Companion)

End Class

Public Class Companion

    Public Property CompanionId As Integer
    Public Property Name As String
    Public Property Actor As String
    Public Property Doctors As List(Of Doctor)

End Class

Public Class DoctorViewModel

    Public Property DoctorId As Integer
    Public Property Actor As String
    Public Property Companions As List(Of CompanionViewModel)

End Class

Public Class CompanionViewModel

    Public Property Actor As String

End Class

我正在尝试获取一位奇异的医生,并附上与他一起旅行的同伴名单。我可以很简单地做到这一点,但我试图塑造查询以仅获取几列而不是整个实体。他是我的拙劣查询 - X 是我无法弄清楚的。

Dim query = From d In context.Doctors
                From c In context.Companions
                Select New DoctorViewModel With {
                    .Actor = d.Actor,
                    .DoctorId = d.DoctorId,
                    .Companions = XXXXXXX}

编辑:如果我查询:

(From d In Tardis.Doctors
 Where d.Actor = "Tom Baker"
 Select New DoctorViewModel With {.Actor = d.Actor, .Companions = d.Companions.Select(Function(c) New CompanionViewModel With {.Actor = c.Actor})}).SingleOrDefault

我得到:

“无法转换类型 'System.Collections.Generic.IEnumerable 1' to type 'System.Collections.Generic.List1'。LINQ to Entities 仅支持转换实体数据模型原始类型。”

放弃查询中的 ViewModel 类并将其作为匿名类型获取,然后将其传递给 ViewModel 中的构造函数(我的模型有一些需要的函数)并像这样填充类会被认为是讨厌的吗?

4

2 回答 2

1

它可能不仅没问题,而且更具可读性(又名可维护)。特别是因为查询不会返回匿名类型,所以它会返回一个 IQueryable

于 2012-05-13T05:49:14.750 回答
0

解决了!我在这上面花了好几天!诀窍是将 Doctor ViewModel 中的 List 更改为IEnumerable(Of CompanionViewModel)

于 2012-05-13T05:51:06.083 回答