Query to Include Discriminator value when using TPH

c# discriminator entity-framework entity-framework-6 tph

Question

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
                                                };
1
1
9/27/2014 5:11:47 AM

Accepted Answer

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.

1
9/26/2014 6:13:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow