开发者

VB.NET Linq to Entities Query with child objects

开发者 https://www.devze.com 2023-04-13 01:52 出处:网络
Basically I have the follwing: 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)

Basically I have the follwing:

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})
                              }

The error i get when i run this i开发者_如何学运维s:

Unable to cast object of type System.Data.Objects.ObjectQuery`1[AdminCoreModel.Role] to type AdminCoreModel.Role

Basically I have a many to many situation and I try to get all the Quicklinks objects queried by their roles and not quite sure why EF will cast to a single AdminCoreModel.Role when i.Roles is a collections of objects.

Any help greatly appreciated


Well, .Contains() expects one Role, and you're passing it a list. That's what the error says.

Try (apologies in advance if I mangle the VB.NET syntax; I don't usually write 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})
                          }
0

精彩评论

暂无评论...
验证码 换一张
取 消