泛型和Entity Framework:我如何取决于列值返回不同类型的 [英] Generics and Entity Framework: How do I return a different type depending on a column value

查看:175
本文介绍了泛型和Entity Framework:我如何取决于列值返回不同类型的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个人表用于存储不同类型的人(买方,卖方,代理等)。我们的ORM是实体框架CodeFirst(CTP5)。我们使用了良好的TDD和嘲讽库模式。在PersonRepository我想返回一个特定的类型,所以我可以做这样的事情:

 代理A = repository.Get<剂> (5005); //其中5005仅仅是一个例子ID为个人
a.SomeAgentProperty = someValue中;
买方B = repository.Get<买方GT;(253); //同样,一个简单的PERSONID。
b.SomeBuyerProperty = someOtherValue;



的想法是,我知道我得到什么样的人,当我从资料库得到它。而且,是的,我可以创建X个不同Get方法称为GetBuyer(INT PERSONID),GetSeller(INT PERSONID)等。但是,这有一个代码味道。



如何将通用功能看?



下面是我的仓库接口,这样远:

 公共接口IPersonRepository 
{
获得的人(INT PERSONID); //为了得到一个通用的人
吨得到< T>(INT PERSONID); //获取特定类型的人(买家,代理等)
无效保存(人的人);
无效删除(INT P);
}

和我的具体落实:

 公开吨得到< T>(INT PERSONID)
{
//这里是我的问题:什么放在这里?
}


解决方案

我会建议使用的东西这样的:

 公开吨得到< T>(INT PERSONID)其中T:新的()
{
返回新的T(PERSONID);
}

在构造函数中

和负荷数据或实施某种形式的Load方法的每种类型你的实体,如:

 接口IEntity 
{
无效负载(INT ID);
}

类CBuyer:IEntity
{
公共负载(INT标识){...}
}

公众吨得到< T>(INT PERSONID)其中T:IEntity,新的()
{$ b $(b T)=耳鼻喉科新T();
ent.Load(PERSONID);
返回耳鼻喉科;
}


We have a Persons table which stores different types of persons (Buyer, Seller, Agent, etc). Our ORM is Entity Framework CodeFirst (CTP5). We're using the repository pattern for good TDD and mocking. In the PersonRepository I want to return a specific type so I can do things like this:

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;

The idea is that I know what kind of person I'm getting when I get it from the repository. And, yes, I could just create X different Get methods called GetBuyer(int PersonId), GetSeller(int PersonId) and so on. But that has a code smell.

How would the generic function look?

Here is my repository interface so far:

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

And my concrete implementation:

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

解决方案

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

这篇关于泛型和Entity Framework:我如何取决于列值返回不同类型的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆