Steve
Steve

Reputation: 387

Query to Include Discriminator value when using TPH

When using TPH I have different types inheriting from a base. We have a search that queries across the abstract type. In the results, we want to show the type:

ie. abstract Vehicle

Car: Vehicle Truck: Vehicle

in the results, I want to show 'type' - ie. 'Car' and 'Truck'.

I attempted to use GetType().Name but this fails.

Here is sample:

 IQueryable<CompanySearchResult> q = from company in _ctx.Companies
                                                select new CompanySearchResult
                                                {                                                        
                                                    CompanyName = company.CompanyName,
                                                    CompanyId = company.Id,
                                                    Type = company.GetType().Name
                                                };

Upvotes: 1

Views: 1314

Answers (1)

Wiktor Zychla
Wiktor Zychla

Reputation: 48314

You have to postpone projection until you have entities in memory

 IEnumerable<CompanySearchResult> q = 
    _ctx.Companies.ToList()
        .Select( company =>
            new CompanySearchResult
            {                                                        
                CompanyName = company.CompanyName,
                CompanyId = company.Id,
                Type = company.GetType().Name
            } );

In particular, this means that you shouldn't still have IQueryable after the projection, as you operate on an in-memory collection.

Upvotes: 1

Related Questions