Search code examples
vb.netentity-frameworklinqlinq-to-entities

Entity Framework - How to return strongly typed IQueryable with joined entities


In my database schema I have a User base table, joined to various other tables used for specific categories of users.

I have an EF query like so...

Dim query = From u In DBContext.Users
            Join a In DBContext.Advertiser On u.UserID Equals a.UserID

This creates an IQueryable of anonymous type including keys 'u' and 'a' containing the entities.

What I'd like to be able to do, is somehow change this be return a strongly typed IQueryable, but I'm not sure how to do it.

What I've tried is creating a class like so...

Class MyAdvertiser
    Public u As User
    Public a As Advertiser
End Class

and then declaring query like so...

Dim query As IQueryable(Of MyAdvertiser) = ...

But it tells me that it can't cast to MyAdvertiser because the anonymous type isn't derived from MyAdvertiser.

I'm probably missing something really obvious. I'm still relatively new at EntityFramework and linq.


Solution

  • You just need to project with a Linq Select. Simply add on the end of your query. For example:

    Dim query = From u In DBContext.Users
                Join a In DBContext.Advertiser On u.UserID Equals a.UserID
                Select New MyAdvertiser With { .u = u, .a = a }