简体   繁体   中英

EF DbSet.Find throws InvalidOperationException

I have two entities connected by TPT inheritance pattern:

public class User {...}
public class Employee : User {...}

As you can see, base class isn't abstract so both entity types can be added into db-sets. There are two separate sets (I need them both in my model):

public DbSet<User> Users { get; set; }
public DbSet<Employee> Employees { get; set; }

So, basically, Users table contains all entities and Employees holds additional data only for objects that were instantiated as new Employee() .

Now, when I try to get entity from Employees set using Find method, I'm expecting that it will only return 'actual' employees. But if I'm specifying Id of the User entity, EF still fetches it from the database and then throws an InvalidOperationException :

"The specified cast from a materialized 'System.Data.Entity.DynamicProxies.User_B2E5EC989E36BE8C53B9285A70C4E879F0B5672E1D141B93FD299D1BA60258EE' type to the 'Data.Employee' type is not valid."

It can't cast User to Employee, which is understandable.

My question is - is there a way to configure TPT inheritance so Find just returns null in such cases as it does when you pass non-existing Id into 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 - so maybe there is a better (more elegant) solution?

我倾向于选择singleordefault()/ firstordefault()而不是find,因为如果没有找到匹配项,它将直接返回null,但是你可以使用像这样的Find的谓词吗?

return Employees.Find(em => em.id == id && em is Employee);

Your are missing your DbContext instance. You can't search on the Table Type coz thats declaration.

var checkfind = dbInstance.Employees.Find(searchedID);

If you don't have access directly to your Db you use

    using (DBLocal db = new DBLocal())
{
    db.Employees.Find(searchedID);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM