实体框架:多对多

时间:2012-05-13 02:38:49

标签: entity-framework ef-code-first many-to-many

我有以下情况:Doctor可以有多个CompanionsCompanion也可以包含多个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.List 1'。 LINQ to Entities only   支持转换实体数据模型基元类型。"

在查询中抛弃ViewModel类并将其作为匿名类型获取,然后将其传递给ViewModel中的构造函数(我的模型有一些需要的函数)并填充这样的课?

2 个答案:

答案 0 :(得分:1)

它可能不仅可以,而且更具可读性(也可维护)。特别是因为查询不会返回匿名类型,它将返回IQueryable

答案 1 :(得分:0)

解决!我花了好几天! Trick是将Doctor ViewModel中的List更改为IEnumerable(Of CompanionViewModel)