使用STI和ActiveRecordBase<>完整的FindAll

时间:2010-05-05 17:48:00

标签: c# generics castle-activerecord single-table-inheritance

是否可以使用单表继承的通用支持,并且仍然能够查找基类的FindAll?

作为奖励问题,我是否可以使用ActiveRecordLinqBase<>还有?我确实喜欢这些疑问。

更多细节: 假设我定义了以下类:

public interface ICompany
{
    int ID { get; set; }
    string Name { get; set; }
}

[ActiveRecord("companies", 
  DiscriminatorColumn="type", 
  DiscriminatorType="String", 
  DiscriminatorValue="NA")]
public abstract class Company<T> : ActiveRecordBase<T>, ICompany
{
    [PrimaryKey]
    private int Id { get; set; }

    [Property]
    public String Name { get; set; }
}

[ActiveRecord(DiscriminatorValue="firm")]
public class Firm : Company<Firm>
{
    [Property]
    public string Description { get; set; }
}

[ActiveRecord(DiscriminatorValue="client")]
public class Client : Company<Client>
{
    [Property]
    public int ChargeRate { get; set; } 
}

这适用于大多数情况。我可以这样做:

var x = Client.FindAll();

但有时我想要所有的公司。如果我没有使用泛型,我可以这样做:

var x = (Company[]) FindAll(Company);
Client a = (Client)x[0];
Firm b = (Firm)x[1];

有没有办法编写一个FindAll,它返回一个ICompany数组,然后可以将它们转换为各自的类型?
类似的东西:

var x = (ICompany[]) FindAll(Company<ICompany>);
Client a = (Client)x[0];

或许我正在实施通用支持所有错误?

1 个答案:

答案 0 :(得分:0)

这个怎么样:

[ActiveRecord("companies", 
  DiscriminatorColumn="type", 
  DiscriminatorType="String", 
  DiscriminatorValue="NA")]
public abstract class Company : ActiveRecordBase<Company>, ICompany {
    [PrimaryKey]
    private virtual int Id { get; set; }

    [Property]
    public virtual String Name { get; set; }
}

[ActiveRecord(DiscriminatorValue="firm")]
public class Firm : Company {
    [Property]
    public virtual string Description { get; set; }
}

[ActiveRecord(DiscriminatorValue="client")]
public class Client : Company {
    [Property]
    public virtual int ChargeRate { get; set; } 
}

var allClients = ActiveRecordMediator<Client>.FindAll();
var allCompanies = ActiveRecordMediator<Company>.FindAll(); // Gets all Companies (Firms and Clients). Same as Company.FindAll();

请注意,您不能只是将您的公司作为客户或公司转发,您需要使用适当的多态性或访问者。有关说明,请参阅this