using DW5S.Entity; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace DW5S.Repostory { public interface IRepository { IQueryable AsQueryable(); Task GetByIdAsync(object id); Task> GetAllAsync(); Task> FindAsync(Expression> predicate); Task> GetDistinctAsync(Expression> selector); Task FirstOrDefaultAsync(Expression> predicate = null); Task AddAsync(T entity); Task AddRangeAsync(IEnumerable entitis); void Update(T entity); void Delete(T entity); Task DeleteAsync(Expression> predicate = null); } public class Repository : IRepository where T : class { protected readonly OracleContext ctx; protected readonly DbSet dbSet; public Repository(OracleContext ctx) { this.ctx = ctx; this.dbSet = ctx.Set(); } public IQueryable AsQueryable() { return dbSet.AsQueryable(); } public async Task GetByIdAsync(object id) { return await dbSet.FindAsync(id); } public async Task> GetAllAsync() { return await dbSet.ToListAsync(); } public async Task> FindAsync(Expression> predicate) { return await dbSet.Where(predicate).ToListAsync(); } public async Task FirstOrDefaultAsync(Expression> predicate = null) { if (predicate != null) return await dbSet.Where(predicate).FirstOrDefaultAsync(); return await dbSet.FirstOrDefaultAsync(); } public async Task> GetDistinctAsync(Expression> selector) { var res = await dbSet.Select(selector).Distinct().ToListAsync(); return res; } public async Task AddAsync(T entity) { var res = await dbSet.AddAsync(entity); return res.Entity; } public async Task AddRangeAsync(IEnumerable entitis) { await dbSet.AddRangeAsync(entitis); } public void Update(T entity) { dbSet.Update(entity); } public void Delete(T entity) { dbSet.Remove(entity); } ///// ///// 高性能的删除 ///// ///// ids可以是int、long、IEnumerable、IEnumerable等类型 //public async void DeleteById(object id) //{ // if (id == null) return; // string table = typeof(T).Name; // if (id is IEnumerable ids1) // { // //如果ID是连续的,这里可以使用大于小于等条件进一步优化 // string sql = $"delete from {table} where id in ({string.Join(",", ids1)})"; // await ctx.ExecuteSqlAsync(sql); // } // else if (id is IEnumerable ids2) // { // string sql = $"delete from {table} where id in ({string.Join(",", ids2)})"; // await ctx.ExecuteSqlAsync(sql); // } // else // { // string sql = $"delete from {table} where id={id}"; // await ctx.ExecuteSqlAsync(sql); // } //} public async Task DeleteAsync(Expression> predicate = null) { return await dbSet.Where(predicate).ExecuteDeleteAsync(); } } }