如何在asp.net mvc中为我的存储库制作无类型接口?

mar*_*rko 2 c# asp.net asp.net-mvc

我有几个存储库,希望它们实现一个接口,但实现方法应该是相同的 - 选择,插入等.但实现方法会改变.你可以做出几种选择,哪种更好?

 interface IRepository
    {
        List<T> Select();
        int Insert(T); 
    }
Run Code Online (Sandbox Code Playgroud)

Dev*_*evT 7

您可以创建界面,该界面可以在您的类中实现.

  public interface IRepository<T> where T:class
    {
        IQueryable<T> GetAll();
        T GetById(object id);
        void Insert(T entity);
        void Update(T entity);         
    }
Run Code Online (Sandbox Code Playgroud)

您也可以在这里使用存储库模式工作单元模式.

 public class Repository<T>:IRepository<T> where T:class
    {
        private DbContext context = null;
        private DbSet<T> dbSet = null;

        public Repository(DbContext context)
        {
            this.context = context;
            this.dbSet = context.Set<T>();
        }

        #region IRepository

        public void Insert(T entity)
        {
            dbSet.Add(entity);
        }

        public IQueryable<T> GetAll()
        {
            return dbSet;
        }

        public void Update(T entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            this.context.SaveChanges();
        }

       #endregion
    }
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以传递任何类型的对象.有关详细信息和示例,请点击此处