using FreeSql; using FreeSql.DataAnnotations; using System; using System.Data; using System.Diagnostics; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; /// /// 包括 CreateTime/UpdateTime/IsDeleted、以及 CRUD 异步方法的实体基类 /// /// [Table(DisableSyncStructure = true)] public abstract class BaseEntityAsync : BaseEntity where TEntity : class { /// /// 查询数据 /// /// public static ISelect Select => Orm.Select() .WithTransaction(UnitOfWork.Current.Value?.GetOrBeginTransaction(false)) .WhereCascade(a => (a as BaseEntity).IsDeleted == false); /// /// 查询条件,Where(a => a.Id > 10),支持导航对象查询,Where(a => a.Author.Email == "2881099@qq.com") /// /// lambda表达式 /// public static ISelect Where(Expression> exp) => Select.Where(exp); /// /// 查询条件,Where(true, a => a.Id > 10),支导航对象查询,Where(true, a => a.Author.Email == "2881099@qq.com") /// /// true 时生效 /// lambda表达式 /// public static ISelect WhereIf(bool condition, Expression> exp) => Select.WhereIf(condition, exp); /// /// 仓储对象 /// protected IBaseRepository Repository { get; set; } /// /// 附加实体,在更新数据时,只更新变化的部分 /// public TEntity Attach() { if (this.Repository == null) this.Repository = Orm.GetRepository(); var item = this as TEntity; this.Repository.Attach(item); return item; } /** async **/ async Task UpdateIsDeletedAsync(bool value) { if (this.Repository == null) return await Orm.Update(this as TEntity) .WithTransaction(UnitOfWork.Current.Value?.GetOrBeginTransaction()) .Set(a => (a as BaseEntity).IsDeleted, this.IsDeleted = value).ExecuteAffrowsAsync() == 1; this.IsDeleted = value; this.Repository.UnitOfWork = UnitOfWork.Current.Value; return await this.Repository.UpdateAsync(this as TEntity) == 1; } /// /// 删除数据 /// /// public virtual Task DeleteAsync() => this.UpdateIsDeletedAsync(true); /// /// 恢复删除的数据 /// /// public virtual Task RestoreAsync() => this.UpdateIsDeletedAsync(false); /// /// 更新数据 /// /// async public virtual Task UpdateAsync() { this.UpdateTime = DateTime.Now; if (this.Repository == null) return await Orm.Update() .WithTransaction(UnitOfWork.Current.Value?.GetOrBeginTransaction()) .SetSource(this as TEntity).ExecuteAffrowsAsync() == 1; this.Repository.UnitOfWork = UnitOfWork.Current.Value; return await this.Repository.UpdateAsync(this as TEntity) == 1; } /// /// 插入数据 /// public virtual Task InsertAsync() { this.CreateTime = DateTime.Now; if (this.Repository == null) this.Repository = Orm.GetRepository(); this.Repository.UnitOfWork = UnitOfWork.Current.Value; return this.Repository.InsertAsync(this as TEntity); } /// /// 更新或插入 /// /// public virtual Task SaveAsync() { this.UpdateTime = DateTime.Now; if (this.Repository == null) this.Repository = Orm.GetRepository(); this.Repository.UnitOfWork = UnitOfWork.Current.Value; return this.Repository.InsertOrUpdateAsync(this as TEntity); } }