'Entity framework core TPH query across different subtype properties
I'm using EF core TPH inheritance to model some data and I'm trying to write a query that will query across different subtypes. My current attempt at writing a query cannot be translated to SQL at run time of the query.
public class NameChange : Change {
public string NewName {get; set;}
}
public class AddressChange : Change {
public string NewAddress {get; set;}
}
public class Change {
public long Id {get; set;}
}
Query:
var changes = _context.Changes.Where(x =>
(x as NameChange).NewName == "john" ||
(x as AddressChange).NewAddress== "123 street").ToList();
This query gives me an InvalidOperationException, is there a way to rewrite it so that I am able to write a single query that will query across different subtype properties? If not then I question if I should be using TPH at all. I am using EF Core version 3.1.
Thanks
Solution 1:[1]
The way I was casting was not supported with my version of EFCore (facepalm). This code snippet works
var changes = _context.Changes.Where(x =>
((NameChange)x).NewName == "john" ||
((AddressChange)x).NewAddress== "123 street").ToList();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user2568701 |