IRepository 与 IDbContext 的实现

IRepositoryBase

public interface IRepositoryBase<T> where T : class
    {
        DbSet<T> Entites { get; } 
        Task CreateAsync(T entity, bool save = true); 
        Task UpdateAsync(T entity, bool save = true);
        Task UpdateAsync(Expression<Func<T, bool>> where, Expression<Func<T, T>> update, bool save = true); 
        Task RemoveAsync(T entity, bool save = true);
        Task RemoveAsync(Expression<Func<T, bool>> where, bool save = true); 
        Task<T> FindAsync(params object[] Id);
        Task<T> QueryFirstAsync(Expression<Func<T, bool>> where); 
         Task<List<T>> QueryAsync(Expression<Func<T, bool>> where = null); 
        Task<List<T>> QueryWithNoTrackingAsync(Expression<Func<T, bool>> where = null); 
        Task<int> SaveChangesAsync(); 
    }


RepositoryBase

public class RepositoryBase<T> : IRepositoryBase<T> where T : class
    {
        private readonly IDbContext db; 

        public RepositoryBase(IDbContext db)
        {
            this.db = db; 
        }

        public DbSet<T> Entites
        {
            get { return db.Set<T>(); }
        }

        public async Task CreateAsync(T entity, bool save = true)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            Entites.Add(entity);
            if (save)
                await SaveChangesAsync();

            await Task.FromResult(0);
        }

        public async Task UpdateAsync(T entity, bool save = true)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            db.Entry(entity).State = EntityState.Modified;

            if (save)
                await SaveChangesAsync();

            await Task.FromResult(0);
        }

        public async Task UpdateAsync(Expression<Func<T, bool>> where, Expression<Func<T, T>> update, bool save = true)
        {
            await Entites.Where(where).UpdateAsync(update);

            if (save)
                await SaveChangesAsync();

            await Task.FromResult(0);
        }

        public async Task RemoveAsync(T entity, bool save = true)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            Entites.Remove(entity);
            if (save)
                await SaveChangesAsync();

            await Task.FromResult(0);
        }

        public async Task RemoveAsync(Expression<Func<T, bool>> where, bool save = true)
        {
            await Entites.Where(where).DeleteAsync();

            if (save)
                await SaveChangesAsync();

            await Task.FromResult(0);
        }

        public Task<T> FindAsync(params object[] Id)
        {
            if (Id == null)
                throw new ArgumentNullException("Id");

            return Entites.FindAsync(Id);
        }

        public Task<T> QueryFirstAsync(Expression<Func<T, bool>> where)
        {
            if (where == null)
                throw new ArgumentNullException("where");

            return Entites.FirstOrDefaultAsync(where);
        } 

        public Task<List<T>> QueryAsync(Expression<Func<T, bool>> where = null)
        {
            if (where == null)
                return Entites.ToListAsync();
            else
                return Entites.Where(where).ToListAsync();
        }

        public Task<List<T>> QueryWithNoTrackingAsync(Expression<Func<T, bool>> where = null)
        {
            if (where == null)
                return Entites.AsNoTracking().ToListAsync();
            else
                return Entites.AsNoTracking().Where(where).ToListAsync();
        }

        public Task<int> SaveChangesAsync()
        {
            try
            {
                return this.db.SaveChangesAsync();
            }
            catch (DbEntityValidationException ex) //保存已中止,因为实体属性值的验证失败。
            {
                var errors = ex.EntityValidationErrors.Select(t => t.ValidationErrors);
                foreach (var err in errors)
                {
                    throw new Exception(err.Select(t => t.ErrorMessage).FirstOrDefault());
                }
            }
            catch (DbUpdateConcurrencyException ex) //数据库命令未影响预期行数。这通常指示存在乐观并发冲突;即,某行自对它查询以来已在数据库中发生更改。
            {
                throw ex;
            }
            catch (DbUpdateException ex) //向数据库发送更新时出错。
            {
                throw ex;
            }
            catch (Exception ex)
            {
                // log.Debug(ex.ToString());
                throw ex;
            }
            return Task.FromResult(0);
        }

    }



IDbContext
public interface IDbContext
    {
        DbSet<TEntity> Set<TEntity>() where TEntity : class;
 
        DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;

        Task<int> SaveChangesAsync();

        bool IsDatabase { get; }

        void CreateDatabase();
        int ExecuteSqlCommand(string sql, params object[] parameters);
    }



DbObjectContext
public class DbObjectContext : DbContext, IDbContext
    { 
        public DbObjectContext()
            : base("default")
        {
            this.Database.Log = s => Log(s);
        }

        static DbObjectContext()
        {
            Database.SetInitializer<DbObjectContext>(null);

            //在应用程序启动时自动升级(MigrateDatabaseToLatestVersion 初始值设定项)
            //Database.SetInitializer<DbObjectContext>(new MigrateDatabaseToLatestVersion<DbObjectContext, Configuration>());
        }

        /// <summary>
        /// SQL日志输出
        /// </summary>
        /// <param name="txt"></param>
        private void Log(string txt)
        {
            //Debug.WriteLine(txt);
        }
 
        public bool IsDatabase
        {
            get { return Database.Exists(); }
        }

        public void CreateDatabase()
        {
            this.Database.Create();
        }

        public int ExecuteSqlCommand(string sql, params object[] parameters)
        {
            if (parameters == null)
                parameters = new SqlParameter[] { };
            return this.Database.ExecuteSqlCommand(TransactionalBehavior.EnsureTransaction, sql, parameters);
        }
    }






你可能感兴趣的:(C#,entityframework)