Domanda

I have a database constructed using code first. I found that querying using projection into a concrete type is by far the fastest method, faster than using Include statements. I run into the following problem however:

dim records=(From record in db.SomeDbSet
             Where record.UserID=userID
             Select New UserSpecificRecord With
             { .Name=record.User.Name
               .Tasks=record.Tasks
             }).ToList

I get different errors when the .Tasks= part is executed, ranging from invalid cast exceptions to messages that the Enity Framework does not support this kind of querying, depending on the type of collection I make the Tasks property of the UserSpecificRecord class.

When I change the code to:

 Dim records= (From record in db.SomeDbSet
                 Where record.UserID=userID
                 Select New With
                 { .Name=record.User.Name
                   .Tasks=record.Tasks
                 }).ToList

   dim userRecords=(From record in records
                    Select New UserSpecificRecord With
                    { .Name=record.Name
                     .Tasks=record.Tasks
                     }).ToList

i.e.: I project to an anonymous type and then build the concrete type it all works. I would very much like to be able to project to the concrete type directly though. Can it be done?

È stato utile?

Soluzione

You cannot project to an 'entity' (is your UserSpecificRecord mapped as well? seems so by the name).
It's not about the 'concrete class`.

See this answer The entity cannot be constructed in a LINQ to Entities query

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top