I have two objects linked by a TPT inheritance pattern:
public class User {...}
public class Employee : User {...}
As you can see, the base class is not abstract, so both types of entities can be added to db sets. There are two separate sets (I need both of them in my model):
public DbSet<User> Users { get; set; }
public DbSet<Employee> Employees { get; set; }
So, basically the table Userscontains all entities and Employeescontains additional data only for objects that were created as new Employee().
Now, when I try to get an object from Employeesusing the method Find, I expect it to return only the "actual" employees. But if I set the identifier of the User object, EF still retrieves it from the database, and then throws InvalidOperationException:
"The specified cast from the materialized 'System.Data.Entity.DynamicProxies.User_B2E5EC989E36BE8C53B9285A70C4E879F0B5672E1D141B93FD299D1BA60258EE' type type Data.Employee is not valid."
It cannot use User to Employee, which is understandable.
My question is: is there a way to configure TPT inheritance, so Find just returns null in cases where it passes a non-existent Id to it.
My current workaround is this:
public Employee GetEmployeeById(int id)
{
try
{
return Employees.Find(id);
}
catch(InvalidOperationException ex) when (ex.Message.StartsWith("The specified cast from a materialized"))
{
return null;
}
}
But I don’t like how it looks - maybe there is a better (more elegant) solution?
drty source
share