我正在考虑为我正在开发的新 ASP.NET MVC 项目创建一个 Entity Framework 4 通用存储库。我一直在查看各种教程,它们似乎都使用工作单元模式......

从我读到的内容来看,EF 已经在 ObjectContext 中使用了它,您只需扩展它来创建您自己的工作单元。

来源: http://dotnet.dzone.com/news/using-unit-work-pattern-entity?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+zones%2Fdotnet+(.NET+Zone)

为什么人们要花这么大的力气去做这件事呢?这是使用通用存储库的首选方式吗?

非常感谢,Kohan。

有帮助吗?

解决方案

这不是我使用通用存储库的方式。首先,我将在当前请求中的 ClassARepository、CalssBRepository 和其他存储库之间共享 ObjectContext。使用 IOC 容器,建议使用注入和按请求行为:

这就是我的通用存储库的样子:

public interface IRepository<T>
{
    //Retrieves list of items in table
    IQueryable<T> List();
    IQueryable<T> List(params string[] includes);
    //Creates from detached item
    void Create(T item);
    void Delete(int id);
    T Get(int id);
    T Get(int id, params string[] includes);
    void SaveChanges();
}

public class Repository<T> : IRepository<T> where T : EntityObject
{
    private ObjectContext _ctx;

    public Repository(ObjectContext ctx)
    {
        _ctx = ctx;
    }


    private static string EntitySetName
    {
        get
        {
            return String.Format(@"{0}Set", typeof(T).Name);
        }
    }

    private ObjectQuery<T> ObjectQueryList()
    {
        var list = _ctx.CreateQuery<T>(EntitySetName);
        return list;
    }

    #region IRepository<T> Members

    public IQueryable<T> List()
    {
        return ObjectQueryList().OrderBy(@"it.ID").AsQueryable();
    }

    public IQueryable<T> List(params string[] includes)
    {
        var list = ObjectQueryList();

        foreach(string include in includes)
        {
            list = list.Include(include);
        }

        return list;
    }

    public void Create(T item)
    {
        _ctx.AddObject(EntitySetName, item);
    }

    public void Delete(int id)
    {
        var item = Get(id);
        _ctx.DeleteObject(item);
    }

    public T Get(int id)
    {
        var list = ObjectQueryList();
        return list.Where("ID = @0", id).First();
    }

    public T Get(int id, params string[] includes)
    {
        var list = List(includes);
        return list.Where("ID = @0", id).First();
    }

    public void SaveChanges()
    {
        _ctx.SaveChanges();
    }

    #endregion

}

ObjectContext 通过构造函数注入。List() 方法返回 IQueryable 以在业务层(服务)对象中进行进一步处理。服务层返回List或IEnumerable,因此视图中不存在延迟执行。

此代码是使用 EF1 创建的。EF4 版本可能略有不同并且更简单。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top