0

リポジトリ パターンを使用して、既存の DB2 スキーマにデータ アクセス層を書き込もうとしています。このスキーマにはいくつかの集約があり、そのすべてが「ドキュメント」という共通の基本エンティティを持っています。ビジネス オブジェクトを構築するとき、Document エンティティを抽象として作成し、集約を Document から派生したエンティティとして作成しました。例えば:

public abstract class Document
{
    public long Id{ get; set; }
    public int PageCount{ get; set; }
    public string Path{ get; set; }
}

public class LegalDocument : Document
{
    public int CaseNumber{ get; set; }
}

public class BillingDocument : Document
{
    public int InvoiceNumber{ get; set; }
    public double AmountDue{ get; set; }
}

ここで、BillingDocument のリポジトリを作成したいと考えていますが、BillingDocument リポジトリにすべての Document ベース プロパティをロードしたくないことがわかっているため、この機能のジェネリック型パラメーターを持つ別の抽象クラスを作成しました。 . ただし、派生した集約エンティティ用にコーディングするリポジトリで使用される抽象的な Document エンティティのインスタンスを返す方法を理解するコーダーのブロックがあります。次のようにリフレクションでそれを行うことができますが、すべてが間違っているように感じます。

abstract class DocumentRepositoryBase<TDocument>
{
    internal Document LoadDocumentBaseProperties(long documentId)
    {
        //Call the database and get the base properties and add them to....this?
        var documentBase = 
            (Document)typeof(TDocument).GetConstructor(Type.EmptyTypes).Invoke(null);
        //Set the documentBase properties
        return documentBase;
    }
}

私はすべてねじれています。誰かがこれで問題ないことを保証してくれますか、それとも私が馬鹿だと言ってより良い方法を教えてくれますか?

前もって感謝します。

4

1 に答える 1

2

次のように、リポジトリ タイプで一般的な制約を使用することを検討してください。

abstract class DocumentRepositoryBase<TDocument>
  // requires it to be a document derivative and have default constructor
  where TDocument : Document, new() 
{
  internal Document LoadDocumentBaseProperties( long documentId )
  {
     var doc = new TDocument();
     return doc;
  }
}

ちなみに、これは抽象クラスのインスタンスを返すのではなく、基本型TDocumentへの参照を介して、(派生物の 1 つ) のインスタンスを返します。Document

于 2009-09-01T21:02:06.420 に答える