1

エンティティ フレームワークでオブジェクトを操作する最善の方法を見つけようとしています。フォームに ObjectContext について何も認識させたくないので、すべてのロジックをエンティティ内に配置します (部分クラスを作成します)。私は他の人の経験をたくさん探してきましたが、このアプローチはどこにも見つかりませんでした. それで、あなたはどのように働きますか?エンティティの状態やその他すべてを失うことなく、ObjectContext からオブジェクトを取得して操作するにはどうすればよいでしょうか? 私はいくつかの解決策に達しましたが、まだ他の人を疑問に思っています。ありがとう。

4

2 に答える 2

3

DDD に従って、エンティティを操作するロジックからエンティティを分離しましょう。個人的には、Repository パターンを使用して、1 つの汎用リポジトリと、エンティティで動作するいくつかの特殊なリポジトリを作成しました。リポジトリは、コンストラクターが指定した ObjectContext で動作するか、何も指定されていない場合は (構成から) 新しいものを作成します。

私の IRepository インターフェイスの例:

public interface IRepository<T> where T : class
{
    /// <summary>
    /// Return all instances of type T.
    /// </summary>
    /// <returns></returns>
    IQueryable<T> All();

    /// <summary>
    /// Return all instances of type T that match the expression exp.
    /// </summary>
    /// <param name="exp"></param>
    /// <returns></returns>
    IEnumerable<T> Find(Func<T, bool> exp);

    /// <summary>Returns the single entity matching the expression. 
    /// Throws an exception if there is not exactly one such entity.</summary>
    /// <param name="exp"></param><returns></returns>
    T Single(Func<T, bool> exp);

    /// <summary>Returns the first element satisfying the condition.</summary>
    /// <param name="exp"></param><returns></returns>
    T First(Func<T, bool> exp);

    /// <summary>
    /// Mark an entity to be deleted when the context is saved.
    /// </summary>
    /// <param name="entity"></param>
    void Delete(T entity);

    /// <summary>
    /// Create a new instance of type T.
    /// </summary>
    /// <returns></returns>
    T CreateInstance();

    /// <summary>Persist the data context.</summary>
    void SaveAll();
}
于 2009-03-04T09:51:11.097 に答える
2

複雑さの順にエンティティ フレームワーク 4 を n 層アーキテクチャに配置する方法の例:

  1. http://devtalk.dk/2009/06/09/Entity+Framework+40+Beta+1+POCO+ObjectSet+Repository+And+UnitOfWork.aspx
  2. http://blog.keithpatton.com/2009/05/30/Entity+Framework+POCO+Repository+Using+Visual+Studio+2010+Net+40+Beta+1.aspx
  3. http://danielwertheim.files.wordpress.com/2009/12/putting-entity-framework-4-to-use-in-a-business-architecture-v2.pdf
  4. http://www.simonsegal.net/blog/2010/01/11/entity-framework-repositories-fetching-strategies-specification-and-mapping-using-nfetchspec-for-role-driven-development-parts-1- 4

ちなみに、@twk によって投稿されたインターフェイスを実装したい場合はIEnumerable<T> Find(Expression<Func<T, bool>> exp);、すべてのクエリ操作に構文を使用してください。実装IEnumerable<T> Find(Func<T, bool> exp);すると、テーブル全体とメモリ内フィルタリングが具体化されます。

于 2010-06-18T05:24:48.327 に答える