1、实体类封装
public interface IEntity<TPrimaryKey> { TPrimaryKey Id { get; set; } bool IsTransient(); } public interface IEntity : IEntity<int> { } public interface IEntityFull<TPrimaryKey> : IEntity<TPrimaryKey> { /// <summary> /// 创建时间 /// </summary> DateTime CreateTime { get; set; } /// <summary> /// 创建人 /// </summary> string CreateOperator { get; set; } /// <summary> /// 最后更新时间 /// </summary> DateTime LastUpdateTime { get; set; } /// <summary> /// 最后更新 /// </summary> string LastUpdateOperator { get; set; } /// <summary> /// 数据的有效性 /// </summary> EnumDataEntityStatus EnumDataEntityStatus { get; set; } } public interface IEntityFull : IEntityFull<int> { } [Serializable] public abstract class Entity<TPrimaryKey> : IEntityFull<TPrimaryKey> { public Entity() { EnumDataEntityStatus = EnumDataEntityStatus.Normal; if (CreateTime == default(DateTime)) { CreateTime = DateTime.Now; } LastUpdateTime = DateTime.Now; } public virtual TPrimaryKey Id { get; set; } public virtual EnumDataEntityStatus EnumDataEntityStatus { get; set; } public virtual DateTime CreateTime { get; set; } public virtual DateTime LastUpdateTime { get; set; } public virtual string CreateOperator { get; set; } public virtual string LastUpdateOperator { get; set; } /// <summary> /// Checks if this entity is transient (it has not an Id). /// </summary> /// <returns>True, if this entity is transient</returns> public virtual bool IsTransient() { if (EqualityComparer<TPrimaryKey>.Default.Equals(Id, default(TPrimaryKey))) { return true; } //Workaround for EF Core since it sets int/long to min value when attaching to dbcontext if (typeof(TPrimaryKey) == typeof(int)) { return Convert.ToInt32(Id) <= 0; } if (typeof(TPrimaryKey) == typeof(long)) { return Convert.ToInt64(Id) <= 0; } return false; } /// <inheritdoc/> public override int GetHashCode() { return Id.GetHashCode(); } /// <inheritdoc/> public override string ToString() { return $"[{GetType().Name} {Id}]"; } } [Serializable] public abstract class Entity : Entity<int>, IEntityFull { } [Table(name: "users", Schema = "dbo")] [Description("用户信息")] public class User : Entity<int> { public User() { this.Account = string.Empty; this.Password = string.Empty; } /// <summary> /// 用户名 /// </summary> [Required] public string Account { get; set; } /// <summary> /// /// </summary> [Required] public string Password { get; set; } /// <summary> /// 用户名称 /// </summary> public string Name { get; set; } /// <summary> /// 性别 /// </summary> public int? Sex { get; set; } /// <summary> /// 业务code /// </summary> public string BizCode { get; set; } /// <summary> /// 用户类型 /// </summary> public int TypeId { get; set; } /// <summary> /// /// </summary> public string TypeName { get; set; } }
2、EF类继承及封装基础操作类
* 需要扩展 Z.EntityFramework.Plus 第三方查件,此插件不仅提供了方便的操作,也提高了EF的效率
* EF DbSet对象使用访问程序及实现
public class EFDbContext : DbContext { //public EFDbContext() // : base("MSDBContext") { // EntityMappers = GetEntityMappers(); //} public EFDbContext(string connectionString) : base(connectionString) { EntityMappers = GetEntityMappers(); } public EFDbContext(DbConnection existingConnection) : base(existingConnection, true) { EntityMappers = GetEntityMappers(); } //public virtual DbSet<User> User { get; set; } private static List<Type> EntityMappers { get; set; } /// <summary> /// 获取需要加载DbSet的类 /// </summary> /// <returns></returns> private List<Type> GetEntityMappers() { List<Type> types = new List<Type>(); CustomAssemblySection configSection = (CustomAssemblySection)System.Configuration.ConfigurationManager.GetSection("CustomAssemblySection"); foreach (CustomAssemblyElement customAssembly in configSection.Assemblies) { Assembly assembly = Assembly.Load(customAssembly.Name); foreach (Type type in assembly.ExportedTypes) { if (!type.IsClass) continue; var tableattrd = type.GetCustomAttribute(typeof(TableAttribute)); if (tableattrd != null) { types.Add(type); } } } return types; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { foreach (var type in EntityMappers) { MethodInfo method = modelBuilder.GetType().GetMethod("Entity"); method = method.MakeGenericMethod(new Type[] { type }); method.Invoke(modelBuilder, null); } base.OnModelCreating(modelBuilder); } } public class BaseRepository<TEntity, TPrimaryKey> : IDisposable,IRepository<TEntity, TPrimaryKey> where TEntity : class, IEntityFull<TPrimaryKey> { /// <summary> /// Gets EF DbContext object. /// </summary> public DbContext DbContext { get; set; } /// <summary> /// /// </summary> private static string AppSettingKey => (ConfigurationManager.AppSettings["DatabaseType"]); /// <summary> /// 默认数据类型 /// </summary> private static EnumDatabaseType _databaseType = (EnumDatabaseType)Enum.Parse(typeof(EnumDatabaseType), AppSettingKey); #region 构造函数 public BaseRepository() :this(_databaseType){ } public BaseRepository(EnumDatabaseType datatype, string connstr) { switch (datatype) { case EnumDatabaseType.MySql: DbContext = new MysqlDbContext(connstr); break; default: DbContext = new MSsqlDbContext(connstr); break; } } /// <summary> /// Constructor /// </summary> /// <param name="dbContext"></param> public BaseRepository(DbContext dbContext) { DbContext = dbContext; } public BaseRepository(EnumDatabaseType datatype,bool isConnection = false) { DbConnection connection = isConnection ? GetDbConnection(AppSettingKey) : null; switch (datatype) { case EnumDatabaseType.MySql: DbContext = isConnection ? new MysqlDbContext(connection) : new MysqlDbContext(); break; default: DbContext = isConnection ? new MSsqlDbContext(connection) : new MSsqlDbContext(); break; } } /// <summary> /// 获取连接 /// </summary> /// <returns></returns> private DbConnection GetDbConnection(string appkey) { DbConnection connection = null; //获取连接字符 var connectionKey = appkey + "Context"; var connectionProvider = ConfigHelper.GetConnString(connectionKey); if (string.IsNullOrEmpty(connectionProvider.ProviderName)) return null; //创建连接 var dbFactory = DbProviderFactories.GetFactory(connectionProvider.ProviderName); connection = dbFactory.CreateConnection(); connection.ConnectionString = connectionProvider.ConnectionString; return connection; } #endregion #region Basic /// <summary> /// 异步提交 /// </summary> /// <returns></returns> public async Task<int> SaveChangesAsync() { return await DbContext.SaveChangesAsync(); } /// <summary> /// 保存 /// </summary> /// <returns></returns> public int SaveChanges() { return DbContext.SaveChanges(); } /// <summary> /// 数据库连接 /// </summary> public DbConnection Connection { get { var connection = DbContext.Database.Connection; if (connection.State != ConnectionState.Open) { connection.Open(); } return connection; } } /// <summary> /// 获取数据 /// </summary> public DbSet<TEntity> Table => DbContext.Set<TEntity>(); /// <summary> /// 获取IQueryable /// </summary> public IQueryable<TEntity> Entities => DbContext.Set<TEntity>(); IQueryable<TEntity> IRepository<TEntity, TPrimaryKey>.Entities => this.Entities; //DbSet<IEntity> IRepository<IEntity, TPrimaryKey>.Table => throw new NotImplementedException(); /// <summary> /// 获取实体所有数据 /// </summary> /// <returns></returns> public IQueryable<TEntity> GetAll() { return Table; } public IQueryable<TEntity> GetIncluding(params Expression<Func<TEntity, object>>[] propertySelectors) { if (propertySelectors == null || !propertySelectors.Any()) { return GetAll(); } var query = GetAll(); foreach (var propertySelector in propertySelectors) { query = query.Include(propertySelector); } return query; } /// <summary> /// /// </summary> /// <param name="entity"></param> protected void AttachIfNot(TEntity entity) { if (!Table.Local.Contains(entity)) { Table.Attach(entity); } } #endregion #region 查询单个对象 /// <summary> /// 根据ID查询实体 /// </summary> /// <param name="id"></param> /// <returns></returns> public TEntity Get(TPrimaryKey id) { return Table.Find(id); } /// <summary> /// 根据ID查询实体 /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<TEntity> GetAsync(TPrimaryKey id) { return await Table.FindAsync(id); } /// <summary> /// 根据条件获取第一条数据 /// </summary> /// <param name="predicate"></param> /// <returns></returns> public TEntity GetFirstOrDefault(Expression<Func<TEntity, bool>> predicate) { return GetAll().FirstOrDefault(predicate); } /// <summary> /// 根据条件获取第一条数据 /// </summary> /// <param name="predicate"></param> /// <returns></returns> public async Task<TEntity> GetFirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate) { return await GetAll().FirstOrDefaultAsync(predicate); } /// <summary> /// 根据条件查询实体 /// </summary> /// <param name="predicates"></param> /// <returns></returns> public TEntity Get(List<Expression<Func<TEntity, bool>>> predicates) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return query.FirstOrDefault(); } /// <summary> /// 根据条件查询实体 /// </summary> /// <param name="predicates"></param> /// <returns></returns> public async Task<TEntity> GetAsync(List<Expression<Func<TEntity, bool>>> predicates) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return await query.FirstOrDefaultAsync(); } #endregion #region 查询列表 /// <summary> /// 获取所有数据 /// </summary> /// <returns></returns> public List<TEntity> GetList() { return GetAll().ToList(); } /// <summary> /// /// </summary> /// <returns></returns> public async Task<List<TEntity>> GetListAsync() { return await GetAll().ToListAsync(); } /// <summary> /// 根据条件获取数据 /// </summary> /// <param name="predicate"></param> /// <returns></returns> public List<TEntity> GetList(Expression<Func<TEntity, bool>> predicate) { return GetAll().Where(predicate).ToList(); } /// <summary> /// 根据条件获取数据 /// </summary> /// <param name="predicate"></param> /// <returns></returns> public async Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> predicate) { return await GetAll().Where(predicate).ToListAsync(); } /// <summary> /// 根据条件集合查询数据 /// </summary> /// <param name="predicates"></param> /// <returns></returns> public List<TEntity> GetList(List<Expression<Func<TEntity, bool>>> predicates) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return query.ToList(); } /// <summary> /// 根据条件集合查询数据 /// </summary> /// <param name="predicates"></param> /// <returns></returns> public async Task<List<TEntity>> GetListAsync(List<Expression<Func<TEntity, bool>>> predicates) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return await query.ToListAsync(); } #endregion #region 分页查询 /// <summary> /// /// </summary> /// <typeparam name="TKey"></typeparam> /// <param name="pageSize">每页显示条数</param> /// <param name="pageIndex">当前页数</param> /// <param name="total">总共条数</param> /// <param name="predicate">条件</param> /// <param name="isAsc">是否顺序</param> /// <param name="orderByLambda">排序字段</param> /// <returns></returns> public IQueryable<TEntity> LoadPagerEntities(int pageSize, int pageIndex, out int total, Expression<Func<TEntity, bool>> predicate, bool isAsc, Expression<Func<TEntity, TPrimaryKey>> orderByLambda) { var tempData = GetAll().Where(predicate); total = tempData.Count(); //排序获取当前页的数据 if (isAsc) { tempData = tempData.OrderBy(orderByLambda). Skip<TEntity>(pageSize * (pageIndex - 1)). Take<TEntity>(pageSize).AsQueryable(); } else { tempData = tempData.OrderByDescending(orderByLambda). Skip<TEntity>(pageSize * (pageIndex - 1)). Take<TEntity>(pageSize).AsQueryable(); } return tempData.AsQueryable(); } /// <summary> /// 分页处理 /// </summary> /// <typeparam name="TKey"></typeparam> /// <param name="pageIndex">当前页数</param> /// <param name="pageSize">每页显示条数</param> /// <param name="orderExpressions"></param> /// <returns></returns> public List<TEntity> GetList(int pageIndex, int pageSize, params OrderParameter<TEntity, TPrimaryKey>[] orderExpressions) { return GetAll().QueryPaged(pageIndex, pageSize, orderExpressions).ToList(); } /// <summary> /// 分页处理 /// </summary> /// <typeparam name="TKey"></typeparam> /// <param name="pageIndex">当前页数</param> /// <param name="pageSize">每页显示条数</param> /// <param name="orderExpressions"></param> /// <returns></returns> public async Task<List<TEntity>> GetListAsync(int pageIndex, int pageSize, params OrderParameter<TEntity, TPrimaryKey>[] orderExpressions) { return await GetAll().QueryPaged(pageIndex, pageSize, orderExpressions).ToListAsync(); } /// <summary> /// 过滤后条件后进行分页处理 /// </summary> /// <param name="predicate">过滤条件</param> /// <param name="pageIndex">当前页数</param> /// <param name="pageSize">每页显示条数</param> /// <param name="orderExpressions"></param> /// <returns>List of all entities</returns> public List<TEntity> GetList(Expression<Func<TEntity, bool>> predicate, int pageIndex, int pageSize, params OrderParameter<TEntity, TPrimaryKey>[] orderExpressions) { return GetAll().Where(predicate).QueryPaged(pageIndex, pageSize, orderExpressions).ToList(); } /// <summary> /// 过滤后条件后进行分页处理 /// </summary> /// <param name="predicate">过滤条件</param> /// <param name="pageIndex">当前页数</param> /// <param name="pageSize">每页显示条数</param> /// <param name="orderExpressions"></param> /// <returns>List of all entities</returns> public async Task<List<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> predicate, int pageIndex, int pageSize, params OrderParameter<TEntity, TPrimaryKey>[] orderExpressions) { return await GetAll().Where(predicate).QueryPaged(pageIndex, pageSize, orderExpressions).ToListAsync(); } /// <summary> /// 过滤后条件后进行分页处理 /// </summary> /// <param name="predicates">过滤条件集</param> /// <param name="pageIndex">当前页数</param> /// <param name="pageSize">每页显示条数</param> /// <param name="orderExpressions"></param> /// <returns>List of all entities</returns> public List<TEntity> GetList(List<Expression<Func<TEntity, bool>>> predicates, int pageIndex, int pageSize, params OrderParameter<TEntity, TPrimaryKey>[] orderExpressions) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return query.QueryPaged(pageIndex, pageSize, orderExpressions).ToList(); } /// <summary> /// 过滤后条件后进行分页处理 /// </summary> /// <param name="predicates">过滤条件集</param> /// <param name="pageIndex">当前页数</param> /// <param name="pageSize">每页显示条数</param> /// <param name="orderExpressions"></param> /// <returns>List of all entities</returns> public async Task<List<TEntity>> GetListAsync(List<Expression<Func<TEntity, bool>>> predicates, int pageIndex, int pageSize, params OrderParameter<TEntity, TPrimaryKey>[] orderExpressions) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return await query.QueryPaged(pageIndex, pageSize, orderExpressions).ToListAsync(); } #endregion #region 新增 /// <summary> /// 插入数据 /// </summary> /// <param name="entity">实体</param> /// <param name="isCommit"></param> /// <returns></returns> public TEntity Insert(TEntity entity, bool isCommit = true) { entity = Table.Add(entity); if (isCommit) { SaveChanges(); } return entity; } /// <summary> /// 插入数据 /// </summary> /// <param name="entity">实体</param> /// <param name="isCommit">是否提交保存</param> /// <returns></returns> public async Task<TEntity> InsertAsync(TEntity entity, bool isCommit = true) { entity = Table.Add(entity); if (isCommit) { await SaveChangesAsync(); } return await Task.FromResult(entity); } /// <summary> /// 插入数据 /// </summary> /// <param name="entity">实体</param> /// <param name="op">操作人</param> /// <param name="isCommit"></param> /// <returns></returns> public TEntity Insert(TEntity entity, Operater op, bool isCommit = true) { SetTraceInfo(entity, op); entity = Table.Add(entity); if (isCommit) { SaveChanges(); } return entity; } /// <summary> /// 插入数据 /// </summary> /// <param name="entity">实体</param> /// <param name="op">操作人</param> /// <param name="isCommit">是否提交保存</param> /// <returns></returns> public async Task<TEntity> InsertAsync(TEntity entity, Operater op, bool isCommit = true) { SetTraceInfo(entity, op); entity = Table.Add(entity); if (isCommit) { await SaveChangesAsync(); } return await Task.FromResult(entity); } /// <summary> /// 插入数据 /// </summary> /// <param name="entity">实体</param> /// <param name="isCommit">是否提交保存</param> /// <returns></returns> public int InsertList(List<TEntity> entitys, bool isCommit = true) { if (entitys == null || !entitys.Any()) return 0; Table.AddRange(entitys); return isCommit ? SaveChanges() : 0; } /// <summary> /// 插入数据 /// </summary> /// <param name="entity">实体</param> /// <param name="isCommit">是否提交保存</param> /// <returns></returns> public async Task<int> InsertListAsync(List<TEntity> entitys, bool isCommit = true) { if (entitys == null || !entitys.Any()) return 0; Table.AddRange(entitys); return isCommit ? await SaveChangesAsync() : await Task.FromResult(0); } /// <summary> /// 插入数据 /// </summary> /// <param name="entity">实体</param> /// <param name="op">操作人</param> /// <param name="isCommit">是否提交保存</param> /// <returns></returns> public int InsertList(List<TEntity> entitys, Operater op, bool isCommit = true) { if (entitys == null || !entitys.Any()) return 0; entitys.ForEach(e => { SetTraceInfo(e, op); }); Table.AddRange(entitys); return isCommit ? SaveChanges() : 0; } /// <summary> /// 插入数据 /// </summary> /// <param name="entity">实体</param> /// <param name="op">操作人</param> /// <param name="isCommit">是否提交保存</param> /// <returns></returns> public async Task<int> InsertListAsync(List<TEntity> entitys, Operater op, bool isCommit = true) { if (entitys == null || !entitys.Any()) return 0; entitys.ForEach(e => { SetTraceInfo(e, op); }); Table.AddRange(entitys); return isCommit ? await SaveChangesAsync() : await Task.FromResult(0); } #endregion #region 更新 /// <summary> /// 更新数据 /// </summary> /// <param name="entity">实体</param> /// <param name="isCommit">是否提交保存</param> /// <returns></returns> public TEntity Update(TEntity entity, bool isCommit = true) { AttachIfNot(entity); DbContext.Entry(entity).State = EntityState.Modified; if (isCommit) { SaveChanges(); } return entity; } /// <summary> /// 更新数据 /// </summary> /// <param name="entity">实体</param> /// <param name="op">操作人</param> /// <param name="isCommit">是否提交保存</param> /// <returns></returns> public async Task<TEntity> UpdateAsync(TEntity entity, bool isCommit = true) { AttachIfNot(entity); DbContext.Entry(entity).State = EntityState.Modified; if (isCommit) { await SaveChangesAsync(); } return await Task.FromResult(entity); } /// <summary> /// 更新数据 /// </summary> /// <param name="entity">实体</param> /// <param name="op">操作人</param> /// <param name="isCommit">是否保存</param> /// <returns></returns> public TEntity Update(TEntity entity, Operater op, bool isCommit = true) { SetTraceInfo(entity, op); AttachIfNot(entity); DbContext.Entry(entity).State = EntityState.Modified; if (isCommit) { SaveChanges(); } return entity; } /// <summary> /// 更新数据 /// </summary> /// <param name="entity">实体</param> /// <param name="op">操作人</param> /// <param name="isCommit">是否保存</param> /// <returns></returns> public async Task<TEntity> UpdateAsync(TEntity entity, Operater op, bool isCommit = true) { SetTraceInfo(entity, op); AttachIfNot(entity); DbContext.Entry(entity).State = EntityState.Modified; if (isCommit) { await SaveChangesAsync(); } return await Task.FromResult(entity); } /// <summary> /// 根据主键id查询 /// </summary> /// <param name="id">主键id</param> /// <param name="updateAction">更新操作</param> /// <param name="isCommit">是否保存</param> /// <returns></returns> public TEntity Update(TPrimaryKey id, Action<TEntity> updateAction, bool isCommit = true) { var entity = Get(id); updateAction(entity); if (isCommit) { SaveChanges(); } return entity; } /// <summary> /// 根据主键id查询 /// </summary> /// <param name="id">主键id</param> /// <param name="updateAction">更新操作</param> /// <param name="isCommit">是否保存</param> /// <returns></returns> public async Task<TEntity> UpdateAsync(TPrimaryKey id, Func<TEntity, Task> updateAction, bool isCommit = true) { var entity = await GetAsync(id); await updateAction(entity); if (isCommit) { await SaveChangesAsync(); } return await Task.FromResult(entity); } /// <summary> /// 根据主键id查询 /// </summary> /// <param name="id">主键id</param> /// <param name="updateAction">更新操作</param> /// <param name="op">操作人</param> /// <param name="isCommit">是否保存</param> /// <returns></returns> public TEntity Update(TPrimaryKey id, Action<TEntity> updateAction, Operater op, bool isCommit = true) { var entity = Get(id); SetTraceInfo(entity, op); updateAction(entity); if (isCommit) { SaveChanges(); } return entity; } /// <summary> /// 根据主键id查询 /// </summary> /// <param name="id">主键id</param> /// <param name="updateAction">更新操作</param> /// <param name="op">操作人</param> /// <param name="isCommit">是否保存</param> /// <returns></returns> public async Task<TEntity> UpdateAsync(TPrimaryKey id, Func<TEntity, Task> updateAction, Operater op, bool isCommit = true) { var entity = await GetAsync(id); SetTraceInfo(entity, op); await updateAction(entity); if (isCommit) { await SaveChangesAsync(); } return await Task.FromResult(entity); } /// <summary> /// 根据条件更新 /// </summary> /// <param name="predicate"></param> /// <param name="updateAction"></param> /// <returns></returns> public int Update(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TEntity>> updateAction) { return GetAll().Where(predicate).Update(updateAction); } /// <summary> /// 根据条件更新 /// </summary> /// <param name="predicate"></param> /// <param name="updateAction"></param> /// <returns></returns> public async Task<int> UpdateAsync(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TEntity>> updateAction) { return await GetAll().Where(predicate).UpdateAsync(updateAction); } /// <summary> /// 根据条件集跟新数据 /// </summary> /// <param name="predicates"></param> /// <param name="updateAction"></param> /// <returns></returns> public int Update(List<Expression<Func<TEntity, bool>>> predicates, Expression<Func<TEntity, TEntity>> updateAction) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return query.Update(updateAction); } /// <summary> /// 根据条件集跟新数据 /// </summary> /// <param name="predicates"></param> /// <param name="updateAction"></param> /// <returns></returns> public async Task<int> UpdateAsync(List<Expression<Func<TEntity, bool>>> predicates, Expression<Func<TEntity, TEntity>> updateAction) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return await query.UpdateAsync(updateAction); } /// <summary> /// 保存数据 /// </summary> /// <param name="entity">实体</param> /// <param name="isCommit">是否保存</param> /// <returns></returns> public TEntity Save(TEntity entity, bool isCommit = true) { if (entity.IsTransient()) { Insert(entity, isCommit); } else { Update(entity, isCommit); } if (isCommit) { SaveChanges(); } return entity; } /// <summary> /// 保存数据 /// </summary> /// <param name="entity">实体</param> /// <param name="isCommit"></param> /// <returns></returns> public async Task<TEntity> SaveAsync(TEntity entity, bool isCommit = true) { if (entity.IsTransient()) { await InsertAsync(entity); } else { await UpdateAsync(entity); } if (isCommit) { await SaveChangesAsync(); } return await Task.FromResult(entity); } /// <summary> /// 保存数据 /// </summary> /// <param name="entity">实体</param> /// <param name="op">操作人</param> /// <param name="isCommit">是否保存</param> /// <returns></returns> public TEntity Save(TEntity entity, Operater op, bool isCommit = true) { SetTraceInfo(entity, op); if (entity.IsTransient()) { Insert(entity, op, isCommit); } else { Update(entity, op, isCommit); } if (isCommit) { SaveChanges(); } return entity; } /// <summary> /// 保存数据 /// </summary> /// <param name="entity">实体</param> /// <param name="isCommit"></param> /// <returns></returns> public async Task<TEntity> SaveAsync(TEntity entity, Operater op, bool isCommit = true) { SetTraceInfo(entity, op); if (entity.IsTransient()) { await InsertAsync(entity); } else { await UpdateAsync(entity); } if (isCommit) { await SaveChangesAsync(); } return await Task.FromResult(entity); } /// <summary> /// 保存数据集 /// </summary> /// <param name="entities"></param> /// <param name="isCommit"></param> /// <returns></returns> public int Save(List<TEntity> entities, bool isCommit = true) { foreach (var entity in entities) { if (entity.IsTransient()) { Insert(entity, false); } else { Update(entity, false); } } return isCommit ? SaveChanges() : 0; } /// <summary> /// 保存数据集 /// </summary> /// <param name="entities"></param> /// <param name="isCommit"></param> /// <returns></returns> public async Task<int> SaveAsync(List<TEntity> entities, bool isCommit = true) { foreach (var entity in entities) { if (entity.IsTransient()) { Insert(entity); } else { Update(entity); } } return isCommit ? await SaveChangesAsync() : await Task.FromResult(0); } /// <summary> /// 保存数据集 /// </summary> /// <param name="entities"></param> /// <param name="isCommit"></param> /// <returns></returns> public int Save(List<TEntity> entities,Operater op, bool isCommit = true) { foreach (var entity in entities) { SetTraceInfo(entity,op); if (entity.IsTransient()) { Insert(entity, false); } else { Update(entity, false); } } return isCommit ? SaveChanges() : 0; } /// <summary> /// 保存数据集 /// </summary> /// <param name="entities"></param> /// <param name="isCommit"></param> /// <returns></returns> public async Task<int> SaveAsync(List<TEntity> entities, Operater op, bool isCommit = true) { foreach (var entity in entities) { SetTraceInfo(entity, op); if (entity.IsTransient()) { Insert(entity); } else { Update(entity); } } return isCommit ? await SaveChangesAsync() : await Task.FromResult(0); } #endregion #region 删除 /// <summary> /// 删除数据 /// </summary> /// <param name="entity"></param> /// <param name="isCommit"></param> /// <returns></returns> public TEntity Delete(TEntity entity, bool isCommit = true) { AttachIfNot(entity); TEntity result = Table.Remove(entity); if (isCommit) { SaveChanges(); } return result ?? default(TEntity); } /// <summary> /// 删除数据 /// </summary> /// <param name="entity"></param> /// <param name="isCommit"></param> /// <returns></returns> public async Task DeleteAsync(TEntity entity, bool isCommit = true) { Table.Remove(entity); if (isCommit) { await SaveChangesAsync(); } } /// <summary> /// 根据id删除数据 /// </summary> /// <param name="id"></param> /// <param name="isCommit"></param> public void Delete(TPrimaryKey id, bool isCommit = true) { var entity = Table.Local.FirstOrDefault(ent => EqualityComparer<TPrimaryKey>.Default.Equals(ent.Id, id)); if (entity == null) { entity = Get(id); if (entity == null) { return; } } Delete(entity, isCommit); } /// <summary> /// 根据id删除数据 /// </summary> /// <param name="id"></param> /// <param name="isCommit"></param> /// <returns></returns> public async Task DeleteAsync(TPrimaryKey id, bool isCommit = true) { var entity = Table.Local.FirstOrDefault(ent => EqualityComparer<TPrimaryKey>.Default.Equals(ent.Id, id)); if (entity == null) { entity = Get(id); if (entity == null) { return; } } await DeleteAsync(entity, isCommit); } /// <summary> /// 根据条件删除数据 /// </summary> /// <param name="predicate"></param> /// <returns></returns> public int Delete(Expression<Func<TEntity, bool>> predicate) { return GetAll().Where(predicate).Delete(); } /// <summary> /// 根据条件删除数据 /// </summary> /// <param name="predicate"></param> /// <returns></returns> public async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate) { await GetAll().Where(predicate).DeleteAsync(); } /// <summary> /// 根据条件集删除数据 /// </summary> /// <param name="predicates"></param> public void Delete(List<Expression<Func<TEntity, bool>>> predicates) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } query.Delete(); } /// <summary> /// 根据条件集删除数据 /// </summary> /// <param name="predicates"></param> /// <returns></returns> public async Task DeleteAsync(List<Expression<Func<TEntity, bool>>> predicates) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } await query.DeleteAsync(); } #endregion #region count /// <summary> /// 获取总数量 /// </summary> /// <returns></returns> public long Count() { return GetAll().LongCount(); } /// <summary> /// 获取总数量 /// </summary> /// <returns></returns> public async Task<long> CountAsync() { return await GetAll().LongCountAsync(); } /// <summary> /// 条件筛选获取总数量 /// </summary> /// <param name="predicate"></param> /// <returns></returns> public long Count(Expression<Func<TEntity, bool>> predicate) { return GetAll().Where(predicate).LongCount(); } /// <summary> /// 条件筛选获取总数量 /// </summary> /// <param name="predicate"></param> /// <returns></returns> public async Task<long> CountAsync(Expression<Func<TEntity, bool>> predicate) { return await GetAll().Where(predicate).LongCountAsync(); } /// <summary> /// 条件集筛选获取总数量 /// </summary> /// <param name="predicates"></param> /// <returns></returns> public long Count(List<Expression<Func<TEntity, bool>>> predicates) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return query.LongCount(); } /// <summary> /// 条件集筛选获取总数量 /// </summary> /// <param name="predicates"></param> /// <returns></returns> public async Task<long> CountAsync(List<Expression<Func<TEntity, bool>>> predicates) { var query = GetAll(); foreach (var expression in predicates) { query = query.Where(expression); } return await query.LongCountAsync(); } #endregion #region 初始化值 Operater private void SetTraceInfo(TEntity entity, Operater operater) { IEntityFull traceEntity = entity as IEntityFull; if (traceEntity != null) { if (traceEntity.Id == 0) { traceEntity.LastUpdateTime = DateTime.Now; traceEntity.LastUpdateOperator = operater.Name; traceEntity.CreateOperator = operater.Name; } else if (!operater.Name.StartsWith("["))//以[开头的操作人是系统程序,只做历史记录,就不在实体本身记录最后操作人。 { traceEntity.LastUpdateTime = DateTime.Now; traceEntity.LastUpdateOperator = operater.Name; } if (traceEntity.LastUpdateTime == default(DateTime)) traceEntity.LastUpdateTime = DateTime.Now; if (!string.IsNullOrEmpty(traceEntity.LastUpdateOperator) && traceEntity.LastUpdateOperator.Length > 50) traceEntity.LastUpdateOperator = traceEntity.LastUpdateOperator.CutString(45); } } #endregion public void Dispose() { this.Connection.Dispose(); this.DbContext.Dispose(); } }
3、mysql和mssql继承继承操作类
public class MSsqlDbContext : EFDbContext { static MSsqlDbContext() { Database.SetInitializer<MSsqlDbContext>(null); } public MSsqlDbContext() : base("SqlServerContext") { } public MSsqlDbContext(string connstr) : base(connstr) { } public MSsqlDbContext(DbConnection existingConnection) : base(existingConnection) { } } [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] public class MysqlDbContext :EFDbContext { static MysqlDbContext() { Database.SetInitializer<MysqlDbContext>(null); } public MysqlDbContext() :base("name=MySqlContext") { } public MysqlDbContext(string connstr) : base(connstr) { } public MysqlDbContext(DbConnection existingConnection) : base(existingConnection) { } }
4、具体实体仓储
public class UserRepository : BaseRepository<User,int>, IUserRepository { }
5、使用
{ for (int i = 0; i < 10; i++) { db.Insert(new User() { Account = "000" + i, Password = "1000" + i, Name = "000" + i, Sex = 0, BizCode = "", TypeId = -1, TypeName = "" }); } var users2 = db.GetList(p=>p.Id>2); db.Update(p => p.Id >= 2, u => new User() { TypeName = "1234" }); db.Delete(p => p.Id > 9); }