Home > database >  Switch on derived table type
Switch on derived table type

Time:12-21

public class Vegetable { }

public class Onion : Vegetable
{
   public string NickName {get; set;}
}

public class Carrot : Vegetable
{
   public string Hypocoristic {get; set;}
}

public async Task<object[]> GetTestObject()
{
    return from ve in _context.Vegetables
    
    let o = ve as Onion
    let c = ve as Carrot
    select new { Name = o != null ? o.NickName : c != null ? c.Hypocoristic  : default;
}

How to apply direct query to DB in order to select different properties based on vegetable type? TPT inheritance is used. The above example translates into a query where it always takes left joined onions table and completely ignores carrots.

CodePudding user response:

Try the following query:

var query = 
    from ve in _context.Vegetables
    select new 
    { 
        Name = ve is Onion ? ((Onion)ve).NickName 
          : ve is Carrot ? ((Carrot)ve).Hypocoristic  
          : default;
    }
  • Related