using FreeSql;
using FreeSql.DataAnnotations;
using System;
using System.Threading.Tasks;
namespace FreeSql
{
///
/// 包括 CreateTime/UpdateTime/IsDeleted、CRUD 异步方法、以及 ID 主键定义 的实体基类
///
/// 当 TKey 为 int/long 时,Id 主键被设为自增值主键
///
///
///
[Table(DisableSyncStructure = true)]
public abstract class BaseEntityAsync : BaseEntityAsync where TEntity : class
{
static BaseEntityAsync()
{
var tkeyType = typeof(TKey)?.NullableTypeOrThis();
if (tkeyType == typeof(int) || tkeyType == typeof(long))
Orm.CodeFirst.ConfigEntity(typeof(TEntity),
t => t.Property("Id").IsIdentity(true));
}
///
/// 主键
///
public virtual TKey Id { get; set; }
///
/// 根据主键值获取数据
///
///
///
async public static Task FindAsync(TKey id)
{
var item = await Select.WhereDynamic(id).FirstAsync();
(item as BaseEntity)?.Attach();
return item;
}
}
///
/// 包括 CreateTime/UpdateTime/IsDeleted、以及 CRUD 异步方法的实体基类
///
///
[Table(DisableSyncStructure = true)]
public abstract class BaseEntityAsync : BaseEntityReadOnly where TEntity : class
{
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.SetTenantId();
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.SetTenantId();
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.SetTenantId();
this.Repository.UnitOfWork = UnitOfWork.Current.Value;
return this.Repository.InsertOrUpdateAsync(this as TEntity);
}
}
}