1

我试图找到在实体框架中处理对象的最佳方式。我不想让我的表单知道任何有关 ObjectContext 的信息,所以我将所有逻辑都放在了实体中(我编写了部分类)。我一直在寻找其他人的经验,但在任何地方都没有找到这种方法。那么,你是如何工作的呢?您如何从 ObjectContext 获取对象并使用它,而不会丢失其实体状态和其他所有内容?我已经找到了一些解决方案,但仍然想知道其他人。谢谢。

4

2 回答 2

3

在 DDD 之后,让我们将您的实体与对其进行操作的逻辑分开。就个人而言,我使用存储库模式来创建一个通用存储库以及一些在我的实体上运行的专用存储库。存储库可以在构造函数给定的 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 回答