Generics and Entity Framework: How do I return a different type depending on a column value

心不动则不痛 提交于 2019-12-04 12:31:18

I would suggest to use something like:

public T Get<T>(int PersonId) where T: new()
{
    return new T(PersonId);
}

and load data in the constructor or implement some kind of Load method for each type of your entity, like:

interface IEntity
{
    void Load(int Id);
}

class CBuyer: IEntity
{
    public Load(int Id) { ... }
}

public T Get<T>(int PersonId) where T: IEntity, new()
{
    T ent = new T();
    ent.Load(PersonId);
    return ent;
}    

Use the OfType<T>() method, which will result in EF doing an INNER JOIN to the specified T if your using TPT, or a filter based on the discriminator if your using TPH.

public TPerson Get<TPerson>(int PersonId) where TPerson : Person
{
    return ctx.People
              .OfType<TPerson>()
              .SingleOrDefault(x => x.PersonId == PersonId);
}

And that will work just like you wanted:

Agent a = repository.Get<Agent>(5005);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!