IRepository,IDbContext

留下备用~~ 微笑

IRepository :

    public interface IRepository<T> : IDisposable where T : class
    {
        DbSet<T> Db { get; }
        Task<T> FindAsync(params object[] Id);

        Task<T> FindAsync(Expression<Func<T, bool>> filterExpression);

        Task CreateAsync(T entity, bool save = true);

        Task UpdateAsync(T entity, bool save = true);

        Task UpdateAsync(Expression<Func<T, bool>> filterExpression, Expression<Func<T, T>> updateExpression, bool save = true);

        Task RemoveAsync(T entity, bool save = true);

        Task RemoveAsync(Expression<Func<T, bool>> filterExpression, bool save = true);

        Task<IQueryable<T>> QueryAsync(Expression<Func<T, bool>> filterExpression = null, bool noTracking = false);

        Task<int> SaveChangesAsync();
    }

Repository :

    public class Repository<T> : IRepository<T> where T : class
    {
        private IDbContext _dbContext;

        public Repository(IDbContext dbContext)
        {
            this._dbContext = dbContext;
        }

        public DbSet<T> Db
        {
            get { return _dbContext.Set<T>(); }
        }

        public async Task<T> FindAsync(params object[] Id)
        {
            return await Db.FindAsync(Id); 
        }

        public async Task<T> FindAsync(Expression<Func<T, bool>> filterExpression)
        {
            return await Db.FirstOrDefaultAsync(filterExpression);
        }

        public async Task CreateAsync(T entity, bool save = true)
        {
            Db.Add(entity);
            if (save)
                await SaveChangesAsync();
        }

        public async Task UpdateAsync(T entity, bool save = true)
        {   
            _dbContext.Entry(entity).State = EntityState.Modified;
            if (save)
                await SaveChangesAsync();
        }

        public async Task UpdateAsync(Expression<Func<T, bool>> filterExpression, Expression<Func<T, T>> updateExpression, bool save = true)
        {
            await Db.Where(filterExpression).UpdateAsync(updateExpression);
            if (save)
                await SaveChangesAsync();
        }

        public async Task RemoveAsync(T entity, bool save = true)
        {
            Db.Remove(entity);
            if (save)
                await SaveChangesAsync();
        }

        public async Task RemoveAsync(Expression<Func<T, bool>> filterExpression, bool save = true)
        {
            await Db.Where(filterExpression).DeleteAsync();
            if (save)
                await SaveChangesAsync();
        }

        public async Task<IQueryable<T>> QueryAsync(Expression<Func<T, bool>> filterExpression = null, bool noTracking = false)
        {
            var query = Db.AsQueryable();
            if (noTracking)
                query = query.AsNoTracking().AsQueryable();
            if (filterExpression != null)
                query = query.Where(filterExpression);

            return await Task.FromResult(query);
        }

        public async Task<int> SaveChangesAsync()
        {
            try
            {
                await _dbContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return await Task.FromResult(0);
        }

        public void Dispose()
        {
            if (_dbContext != null)
                _dbContext.Dispose();
        }
    }

RepositoryExtensions :

    public static class RepositoryExtensions
    {
        public static T Find<T>(this IRepository<T> repository, params object[] Id) where T : class
        {
            return AsyncHelper.RunSync(() => repository.FindAsync(Id));
        }

        public static T Find<T>(this IRepository<T> repository, Expression<Func<T, bool>> filterExpression) where T : class
        {
            return AsyncHelper.RunSync(() => repository.FindAsync(filterExpression));
        }

        public static void Create<T>(this IRepository<T> repository, T entity, bool save = true) where T : class
        {
            AsyncHelper.RunSync(() => repository.CreateAsync(entity, save));
        }

        public static void Update<T>(this IRepository<T> repository, T entity, bool save = true) where T : class
        {
            AsyncHelper.RunSync(() => repository.UpdateAsync(entity, save));
        }

        public static void Update<T>(this IRepository<T> repository, Expression<Func<T, bool>> filterExpression, Expression<Func<T, T>> updateExpression, bool save = true) where T : class
        {
            AsyncHelper.RunSync(() => repository.UpdateAsync(filterExpression, updateExpression, save));
        }

        public static void Remove<T>(this IRepository<T> repository, T entity, bool save = true) where T : class
        {
            AsyncHelper.RunSync(() => repository.RemoveAsync(entity, save));
        }

        public static void Remov<T>(this IRepository<T> repository, Expression<Func<T, bool>> filterExpression, bool save = true) where T : class
        {
            AsyncHelper.RunSync(() => repository.RemoveAsync(filterExpression, save));
        }

        public static IQueryable<T> Query<T>(this IRepository<T> repository, Expression<Func<T, bool>> filterExpression = null, bool noTracking = false) where T : class
        {
            return AsyncHelper.RunSync<IQueryable<T>>(() => repository.QueryAsync(filterExpression, noTracking)).AsQueryable();
        } 
    }

IDbContext :

    /// <summary>
    /// dbContext interface
    /// </summary>
    public interface IDbContext : IDisposable
    {
        /// <summary>
        /// Returns a System.Data.Entity.DbSet<TEntity> instance for access to entities of the given type in the context and the underlying store.
        /// </summary>
        DbSet<TEntity> Set<TEntity>() where TEntity : class;
        /// <summary>
        ///  Gets a System.Data.Entity.Infrastructure.DbEntityEntry<TEntity> object for the given entity providing access to information about the entity and the  ability to perform actions on the entity.
        /// </summary>
        DbEntityEntry Entry(object entity);
        /// <summary>
        ///  Gets a System.Data.Entity.Infrastructure.DbEntityEntry<TEntity> object for the given entity providing access to information about the entity and the  ability to perform actions on the entity.
        /// </summary>
        DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
        /// <summary>
        /// Asynchronously saves all changes made in this context to the underlying database.
        /// </summary>
        /// <returns></returns>
        Task<int> SaveChangesAsync();

    }

DbContext :

    public class WebDbContext : DbContext, IDbContext
    {
        public WebDbContext()
            : base("default")
        { }

        static WebDbContext()
        {
            //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<WebDbContext>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            var typesToRegister = Assembly.GetExecutingAssembly().GetTypes().
                Where(type => !String.IsNullOrEmpty(type.Namespace)).
                Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }

            base.OnModelCreating(modelBuilder);

        }
    }