簡體   English   中英

泛型和實體框架:如何根據列值返回不同的類型

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

我們有一個人員表,存儲不同類型的人(買方,賣方,代理等)。 我們的ORM是實體框架CodeFirst(CTP5)。 我們正在使用存儲庫模式進行良好的TDD和模擬。 在PersonRepository中我想返回一個特定的類型,所以我可以做這樣的事情:

Agent a = repository.Get<Agent>(5005);  // Where 5005 is just an example Id for the person
a.SomeAgentProperty = someValue;
Buyer b = repository.Get<Buyer>(253);   // Again, a simple PersonId.
b.SomeBuyerProperty = someOtherValue;

我的想法是,當我從存儲庫中獲取它時,我知道我會得到什么樣的人。 並且,是的,我可以創建X個不同的Get方法,稱為GetBuyer(int PersonId),GetSeller(int PersonId)等等。 但那有代碼味道。

泛型函數看起來如何?

到目前為止,這是我的存儲庫界面:

public interface IPersonRepository
{
    Person Get(int PersonId);   // To get a generic person
    T Get<T>(int PersonId);     // To get a specific type of person (buyer, agent, etc.)
    void Save(Person person);
    void Delete(int p);
}

我的具體實施:

    public T Get<T>(int PersonId)
    {
        //Here's my question: What goes here?
    }

使用OfType<T>()方法,如果使用TPT,將導致EF對指定的T執行INNER JOIN,如果使用TPH,則使用基於鑒別器的過濾器。

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

這將像你想要的那樣工作:

Agent a = repository.Get<Agent>(5005);

我建議使用類似的東西:

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

並在構造函數中加載數據或為您的每個實體類型實現某種Load方法,例如:

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;
}    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM