使用旧的ado.net实现通用存储库模式

时间:2012-05-23 21:12:08

标签: c# design-patterns orm domain-driven-design repository-pattern

由于平台限制,我正在尝试使用ado.net实现存储库模式。

public interface IGenericRepository<T> : IDisposable where T : class
{
    IQueryable<T> GetAll();
    IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
    void Add(T entity);
    void Delete(T entity);
    void Edit(T entity);
    void Save();
}

如何完成以下抽象类......?

public abstract class GenericRepository<C, T> :
    IGenericRepository<T>
    where T : class
    where C : IDbDataAdapter, new()
{

    private C dbDataAdapter = new C();
    protected C DB
    {
        get { return dbDataAdapter; }
        set { dbDataAdapter = value; }
    }

    public virtual IQueryable<T> GetAll()
    {
        DataTable dt;
        dbDataAdapter.fill(dt);
        IQueryable<T> query = dt....?;
        return query;
    }

    public IQueryable<T> FindBy(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {

        IQueryable<T> query = dbDataAdapter.???Set<T>???().Where(predicate);
        return query;
    }

更新
稍后我将通过固有的这两个接口/类来实现域指定的存储库。

public class FooRepository :
    GenericRepository<FooBarEntities, Foo>, IFooRepository {

    public Foo GetSingle(int fooId) {

        var query = GetAll().FirstOrDefault(x => x.FooId == fooId);
        return query;
    }
}

4 个答案:

答案 0 :(得分:6)

拥有通用存储库通常不是一个好主意。存储库是一个重要的域概念,您不希望过度概括它,就像您不想概括您的实体一样。通用存储库是CRUDy,将焦点从您的域转移。请考虑this article by Greg Young

在相关说明中,除了使代码更少以及更多数据驱动之外,公开IQueryable还会引入tight coupling

答案 1 :(得分:0)

您正在尝试构建典型OR映射器的一部分。这是很多的工作。为什么不使用ORM?

答案 2 :(得分:0)

如果您要从充满不一致性的遗留数据库和大量存储过程中进行操作并尝试将其连接到ORM / Repository模式,那么您可能会发现自己对实现Generic感到非常沮丧存储库模式。

我知道Generic Repository模式在教程部分是一个巨大的打击,当时许多较新的应用程序让像Entity Framework和Active Record这样的东西构成了数据库(记住这种风格意味着没有存储过程或它们的最小用途)。在这些较新的场景中,数据往往更加清晰,并且很容易将其连接到一些通用的存储库模式,因为每个实体都有一个ID。

答案 3 :(得分:0)

不是主题,但我有类似的问题,这是我的解决方案(任何人都可以帮助)

创建身份类:

public class Identity
    {
        public int Id { get; set; }
    }

创建entyty类:

public class Employee: Identity
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }

存储库接口(也只能使用抽象类):

interface IRepository<T> where T: Identity
    {
        T GetById(int id);
        ICollection<T> GetAll();
        ICollection<T> GetAll(string where);
        void Update(T entity);
        void Insert(T entity);
        bool Delete(T entity);
        bool Delete(ICollection<T> entityes);
    }

创建通用抽象类:

public abstract class AbstractRepository<T>: IRepository<T> where T : Identity
    {
        protected abstract string TableName { get; }

        protected abstract T DataRowToModel(DataRow dr);

        protected virtual ICollection<T> DataTableToCollection(DataTable dt)
        {
            if (dt == null)
            {
                return null;
            }
            return dt.AsEnumerable().Select(x => DataRowToModel(x)).ToList();
        }

        public virtual T GetById(int id)
        {
            var query = $"select * from {TableName} where id = {id}";
            //the data access layer is implemented elsewhere
            DataRow dr = DAL.SelectDataRow(query); 
            return DataRowToModel(dr);
        }

        public virtual void Delete(T entity)
        {
            if (entity.Id == 0 )
            {
                return;
            }
            var query = $"delete from {TableName} where id = {entity.Id}";
            DAL.Query(query);
        }

        public virtual void Delete(ICollection<T> entityes)
        {
            var collectionId = IdentityCollectionToSqlIdFormat(entityes);
            if (string.IsNullOrEmpty(collectionId))
            {
                return;
            }
            var query = $"delete from {TableName} where id in ({collectionId})";
            DAL.Query(query);
        }

        public virtual ICollection<T> GetAll()
        {
            var query = $"select * from {TableName}";
            DataTable dt = DAL.SelectDataTable(query);
            return DataTableToCollection(dt);
        }

        public virtual ICollection<T> GetAll(string where)
        {
            var query = $"select * from {TableName} where {where}";
            DataTable dt = DAL.SelectDataTable(query);
            return DataTableToCollection(dt);
        }

        protected virtual string IdentityCollectionToSqlIdFormat(ICollection<T> collection)
        {
            var array = collection.Select(x => x.Id);
            return string.Join(",", array);
        }

        public abstract bool Update(T entity);
        public abstract bool Insert(T entity);
    }

实现EmployeeRepository:

public class EmployeeRepository : AbstractRepository<Employe>
    {
        protected sealed override string TableName
        {
            get
            {
                return "dbo.Employees";
            }
        }

        protected sealed override Employe DataRowToModel(DataRow dr)
        {
            if (dr == null)
            {
                return null;
            }
            return new Employe
            {
                Id = dr.Field<int>("id"),
                Name = dr.Field<string>("name"),
                Surname = dr.Field<string>("surname"),
                Age = dr.Field<int>("age")

            };
        }


        public override void Insert(Employe entity)
        {
            var query = $@"insert into {TableName} (name, surname, age)
                            values({entity.Name},{entity.Surname},{entity.Age})";
            DAL.Query(query);
        }

        public override bool Update(Employe entity)
        {
            throw new NotImplementedException();
        }
    }

就是这样。在代码中使用:

    public class SomeService
{
    public void SomeeMethod()
    {
     int employeeId = 10; // for example
     EmployeeRepository repository = new EmployeeRepository();
     Employee employee = repository.GetById(employeeId);
     repository.Delete(employee);
     //...
    }
    }