VB.NET Linq to Entities查询子对象

时间:2011-10-13 21:50:38

标签: vb.net linq-to-entities parent-child

基本上我有以下内容:

Dim ctx As New AdminCoreEntities
Dim roles = (From r In ctx.Roles where r.Name.StartsWith("cust") Select r) 'list of System.Linq.IQueryable(Of AdminCoreModel.Role)

 Dim items = From i In ctx.QuickLinks.Include("Roles")
             Where (i.TenantID = "470556ba-3574-4b01-a619-b85e9721b966" AndAlso i.Roles.Contains(roles))
             Select New With {
                               i.ID,
                               i.Name,
                               .Roles = (From r In i.Roles Select New With {.Id = r.ID, .Name = r.Name})
                              }

我运行时遇到的错误是:

无法转换System.Data.Objects.ObjectQuery`1 [AdminCoreModel.Role]类型的对象以键入AdminCoreModel.Role

基本上我有很多种情况,我试图让他们的角色查询所有Quicklinks对象 并且不太确定当i.Roles是一个对象集合时,为什么EF会强制转换为单个AdminCoreModel.Role。

任何帮助非常感谢

1 个答案:

答案 0 :(得分:1)

好吧,.Contains()需要一个Role,而你正在传递一个列表。这就是错误所说的。

尝试(如果我破坏VB.NET语法,请提前道歉;我通常不会编写VB.NET):

Dim ctx As New AdminCoreEntities
Dim items = From i In ctx.QuickLinks  ' You don't need Include because you're projecting.
            Where (i.TenantID = "470556ba-3574-4b01-a619-b85e9721b966" 
                   AndAlso i.Roles.Any(Function(role) role.Name.StartsWith("cust"))
            Select New With {
                                i.ID,
                                i.Name,
                                 .Roles = (From r In i.Roles Select New With {.Id = r.ID, .Name = r.Name})
                          }