繁体   English   中英

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

[英]Implement a generic repository pattern using old ado.net

我试图使用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;
    }
}

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

在相关的说明中,除了使代码更少和更多数据驱动之外,公开IQueryable还会引入紧耦合

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

如果你要从一个充满不一致性的遗留数据库,以及大量的存储过程,并且你试图将它连接到ORM / Repository模式,那么你可能会发现自己对实现Generic Repository模式感到非常沮丧。

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

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

创建Identity类:

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);
     //...
    }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM