Merge pull request #849 from alexinea/master

Add English comments for BaseEntity extension package.
This commit is contained in:
IGeekFan 2021-08-10 23:20:20 +08:00 committed by GitHub
commit a5b5af4024
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 242 additions and 152 deletions

View File

@ -1,17 +1,24 @@
using FreeSql; #if NET40
using FreeSql.DataAnnotations;
using System;
#else
using FreeSql.DataAnnotations; using FreeSql.DataAnnotations;
using System; using System;
using System.Data;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#endif
// ReSharper disable once CheckNamespace
namespace FreeSql namespace FreeSql
{ {
/// <summary> /// <summary>
/// Entity base class, including CreateTime/UpdateTime/IsDeleted, the CRUD methods, and ID primary key definition.
/// <para></para>
/// 包括 CreateTime/UpdateTime/IsDeleted、CRUD 方法、以及 ID 主键定义 的实体基类 /// 包括 CreateTime/UpdateTime/IsDeleted、CRUD 方法、以及 ID 主键定义 的实体基类
/// <para></para> /// <para></para>
/// When TKey is int/long, the Id is set to be an auto-incremented primary key
/// <para></para>
/// 当 TKey 为 int/long 时Id 主键被设为自增值主键 /// 当 TKey 为 int/long 时Id 主键被设为自增值主键
/// </summary> /// </summary>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
@ -21,25 +28,26 @@ namespace FreeSql
{ {
static BaseEntity() static BaseEntity()
{ {
var tkeyType = typeof(TKey)?.NullableTypeOrThis(); var keyType = typeof(TKey).NullableTypeOrThis();
if (tkeyType == typeof(int) || tkeyType == typeof(long)) if (keyType == typeof(int) || keyType == typeof(long))
BaseEntity.ConfigEntity(typeof(TEntity), t => t.Property("Id").IsIdentity(true)); ConfigEntity(typeof(TEntity), t => t.Property("Id").IsIdentity(true));
} }
/// <summary> /// <summary>
/// Primary key <br />
/// 主键 /// 主键
/// </summary> /// </summary>
[Column(Position = 1)] [Column(Position = 1)]
public virtual TKey Id { get; set; } public virtual TKey Id { get; set; }
#if net40 #if !NET40
#else
/// <summary> /// <summary>
/// Get data based on the value of the primary key <br />
/// 根据主键值获取数据 /// 根据主键值获取数据
/// </summary> /// </summary>
/// <param name="id"></param> /// <param name="id"></param>
/// <returns></returns> /// <returns></returns>
async public static Task<TEntity> FindAsync(TKey id) public static async Task<TEntity> FindAsync(TKey id)
{ {
var item = await Select.WhereDynamic(id).FirstAsync(); var item = await Select.WhereDynamic(id).FirstAsync();
(item as BaseEntity<TEntity>)?.Attach(); (item as BaseEntity<TEntity>)?.Attach();
@ -48,6 +56,7 @@ namespace FreeSql
#endif #endif
/// <summary> /// <summary>
/// Get data based on the value of the primary key <br />
/// 根据主键值获取数据 /// 根据主键值获取数据
/// </summary> /// </summary>
/// <param name="id"></param> /// <param name="id"></param>
@ -61,6 +70,8 @@ namespace FreeSql
} }
/// <summary> /// <summary>
/// Entity base class, including CreateTime/UpdateTime/IsDeleted, and sync/async CRUD methods.
/// <para></para>
/// 包括 CreateTime/UpdateTime/IsDeleted、以及 CRUD 异步和同步方法的实体基类 /// 包括 CreateTime/UpdateTime/IsDeleted、以及 CRUD 异步和同步方法的实体基类
/// </summary> /// </summary>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
@ -69,88 +80,97 @@ namespace FreeSql
{ {
bool UpdateIsDeleted(bool value) bool UpdateIsDeleted(bool value)
{ {
if (this.Repository == null) if (Repository is null)
{
return Orm.Update<TEntity>(this as TEntity) return Orm.Update<TEntity>(this as TEntity)
.WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction()) .WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction())
.Set(a => (a as BaseEntity).IsDeleted, this.IsDeleted = value).ExecuteAffrows() == 1; .Set(a => (a as BaseEntity).IsDeleted, IsDeleted = value).ExecuteAffrows() == 1;
}
this.IsDeleted = value; IsDeleted = value;
this.Repository.UnitOfWork = _resolveUow?.Invoke(); Repository.UnitOfWork = _resolveUow?.Invoke();
return this.Repository.Update(this as TEntity) == 1; return Repository.Update(this as TEntity) == 1;
} }
/// <summary> /// <summary>
/// To delete data <br />
/// 删除数据 /// 删除数据
/// </summary> /// </summary>
/// <param name="physicalDelete">是否物理删除</param> /// <param name="physicalDelete">To flag whether to delete the physical level of the data</param>
/// <returns></returns> /// <returns></returns>
public virtual bool Delete(bool physicalDelete = false) public virtual bool Delete(bool physicalDelete = false)
{ {
if (physicalDelete == false) return this.UpdateIsDeleted(true); if (physicalDelete == false)
if (this.Repository == null) return UpdateIsDeleted(true);
if (Repository is null)
return Orm.Delete<TEntity>(this as TEntity).ExecuteAffrows() == 1; return Orm.Delete<TEntity>(this as TEntity).ExecuteAffrows() == 1;
this.Repository.UnitOfWork = _resolveUow?.Invoke(); Repository.UnitOfWork = _resolveUow?.Invoke();
return this.Repository.Delete(this as TEntity) == 1; return Repository.Delete(this as TEntity) == 1;
} }
/// <summary> /// <summary>
/// To recover deleted data <br />
/// 恢复删除的数据 /// 恢复删除的数据
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public virtual bool Restore() => this.UpdateIsDeleted(false); public virtual bool Restore() => UpdateIsDeleted(false);
/// <summary> /// <summary>
/// To update data <br />
/// 更新数据 /// 更新数据
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public virtual bool Update() public virtual bool Update()
{ {
this.UpdateTime = DateTime.Now; UpdateTime = DateTime.Now;
if (this.Repository == null) if (Repository is null)
{
return Orm.Update<TEntity>() return Orm.Update<TEntity>()
.WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction()) .WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction())
.SetSource(this as TEntity).ExecuteAffrows() == 1; .SetSource(this as TEntity).ExecuteAffrows() == 1;
}
this.Repository.UnitOfWork = _resolveUow?.Invoke(); Repository.UnitOfWork = _resolveUow?.Invoke();
return this.Repository.Update(this as TEntity) == 1; return Repository.Update(this as TEntity) == 1;
} }
/// <summary> /// <summary>
/// To insert data <br />
/// 插入数据 /// 插入数据
/// </summary> /// </summary>
public virtual TEntity Insert() public virtual TEntity Insert()
{ {
this.CreateTime = DateTime.Now; CreateTime = DateTime.Now;
if (this.Repository == null) Repository ??= Orm.GetRepository<TEntity>();
this.Repository = Orm.GetRepository<TEntity>(); Repository.UnitOfWork = _resolveUow?.Invoke();
return Repository.Insert(this as TEntity);
this.Repository.UnitOfWork = _resolveUow?.Invoke();
return this.Repository.Insert(this as TEntity);
} }
/// <summary> /// <summary>
/// To insert or update data <br />
/// 更新或插入 /// 更新或插入
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public virtual TEntity Save() public virtual TEntity Save()
{ {
this.UpdateTime = DateTime.Now; UpdateTime = DateTime.Now;
if (this.Repository == null) Repository ??= Orm.GetRepository<TEntity>();
this.Repository = Orm.GetRepository<TEntity>(); Repository.UnitOfWork = _resolveUow?.Invoke();
return Repository.InsertOrUpdate(this as TEntity);
this.Repository.UnitOfWork = _resolveUow?.Invoke();
return this.Repository.InsertOrUpdate(this as TEntity);
} }
/// <summary> /// <summary>
/// To completely save the navigation properties of the entity in the form of sub-tables. <br />
/// 【完整】保存导航属性,子表 /// 【完整】保存导航属性,子表
/// </summary> /// </summary>
/// <param name="navigatePropertyName">导航属性名</param> /// <param name="navigatePropertyName">Navigation property name</param>
public virtual void SaveMany(string navigatePropertyName) public virtual void SaveMany(string navigatePropertyName)
{ {
if (this.Repository == null) Repository ??= Orm.GetRepository<TEntity>();
this.Repository = Orm.GetRepository<TEntity>(); Repository.UnitOfWork = _resolveUow?.Invoke();
Repository.SaveMany(this as TEntity, navigatePropertyName);
this.Repository.UnitOfWork = _resolveUow?.Invoke();
this.Repository.SaveMany(this as TEntity, navigatePropertyName);
} }
} }
} }

View File

@ -1,14 +1,23 @@
 #if NET40
using FreeSql; using FreeSql.DataAnnotations;
#else
using FreeSql.DataAnnotations; using FreeSql.DataAnnotations;
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
#endif
// ReSharper disable once CheckNamespace
namespace FreeSql namespace FreeSql
{ {
/// <summary> /// <summary>
/// Entity base class, including CreateTime/UpdateTime/IsDeleted, the async CRUD methods, and ID primary key definition.
/// <para></para>
/// 包括 CreateTime/UpdateTime/IsDeleted、CRUD 异步方法、以及 ID 主键定义 的实体基类 /// 包括 CreateTime/UpdateTime/IsDeleted、CRUD 异步方法、以及 ID 主键定义 的实体基类
/// <para></para> /// <para></para>
/// When TKey is int/long, the Id is set to be an auto-incremented primary key
/// <para></para>
/// 当 TKey 为 int/long 时Id 主键被设为自增值主键 /// 当 TKey 为 int/long 时Id 主键被设为自增值主键
/// </summary> /// </summary>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
@ -18,127 +27,137 @@ namespace FreeSql
{ {
static BaseEntityAsync() static BaseEntityAsync()
{ {
var tkeyType = typeof(TKey)?.NullableTypeOrThis(); var keyType = typeof(TKey).NullableTypeOrThis();
if (tkeyType == typeof(int) || tkeyType == typeof(long)) if (keyType == typeof(int) || keyType == typeof(long))
BaseEntity.ConfigEntity(typeof(TEntity), t => t.Property("Id").IsIdentity(true)); ConfigEntity(typeof(TEntity), t => t.Property("Id").IsIdentity(true));
} }
/// <summary> /// <summary>
/// Primary key <br />
/// 主键 /// 主键
/// </summary> /// </summary>
[Column(Position = 1)] [Column(Position = 1)]
public virtual TKey Id { get; set; } public virtual TKey Id { get; set; }
#if net40 #if !NET40
#else
/// <summary> /// <summary>
/// Get data based on the value of the primary key <br />
/// 根据主键值获取数据 /// 根据主键值获取数据
/// </summary> /// </summary>
/// <param name="id"></param> /// <param name="id"></param>
/// <returns></returns> /// <returns></returns>
async public static Task<TEntity> FindAsync(TKey id) public static async Task<TEntity> FindAsync(TKey id)
{ {
var item = await Select.WhereDynamic(id).FirstAsync(); var item = await Select.WhereDynamic(id).FirstAsync();
(item as BaseEntity<TEntity>)?.Attach(); (item as BaseEntity<TEntity>)?.Attach();
return item; return item;
} }
#endif #endif
} }
/// <summary> /// <summary>
/// Entity base class, including CreateTime/UpdateTime/IsDeleted, and async CRUD methods.
/// <para></para>
/// 包括 CreateTime/UpdateTime/IsDeleted、以及 CRUD 异步方法的实体基类 /// 包括 CreateTime/UpdateTime/IsDeleted、以及 CRUD 异步方法的实体基类
/// </summary> /// </summary>
/// <typeparam name="TEntity"></typeparam> /// <typeparam name="TEntity"></typeparam>
[Table(DisableSyncStructure = true)] [Table(DisableSyncStructure = true)]
public abstract class BaseEntityAsync<TEntity> : BaseEntityReadOnly<TEntity> where TEntity : class public abstract class BaseEntityAsync<TEntity> : BaseEntityReadOnly<TEntity> where TEntity : class
{ {
#if net40 #if !NET40
#else
async Task<bool> UpdateIsDeletedAsync(bool value) async Task<bool> UpdateIsDeletedAsync(bool value)
{ {
if (this.Repository == null) if (Repository is null)
{
return await Orm.Update<TEntity>(this as TEntity) return await Orm.Update<TEntity>(this as TEntity)
.WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction()) .WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction())
.Set(a => (a as BaseEntity).IsDeleted, this.IsDeleted = value).ExecuteAffrowsAsync() == 1; .Set(a => (a as BaseEntity).IsDeleted, IsDeleted = value).ExecuteAffrowsAsync() == 1;
}
this.IsDeleted = value; IsDeleted = value;
this.Repository.UnitOfWork = _resolveUow?.Invoke(); Repository.UnitOfWork = _resolveUow?.Invoke();
return await this.Repository.UpdateAsync(this as TEntity) == 1; return await Repository.UpdateAsync(this as TEntity) == 1;
} }
/// <summary> /// <summary>
/// To delete data <br />
/// 删除数据 /// 删除数据
/// </summary> /// </summary>
/// <param name="physicalDelete">是否物理删除</param> /// <param name="physicalDelete">To flag whether to delete the physical level of the data</param>
/// <returns></returns> /// <returns></returns>
async public virtual Task<bool> DeleteAsync(bool physicalDelete = false) public virtual async Task<bool> DeleteAsync(bool physicalDelete = false)
{ {
if (physicalDelete == false) return await this.UpdateIsDeletedAsync(true); if (physicalDelete == false)
if (this.Repository == null) return await UpdateIsDeletedAsync(true);
if (Repository is null)
return await Orm.Delete<TEntity>(this as TEntity).ExecuteAffrowsAsync() == 1; return await Orm.Delete<TEntity>(this as TEntity).ExecuteAffrowsAsync() == 1;
this.Repository.UnitOfWork = _resolveUow?.Invoke(); Repository.UnitOfWork = _resolveUow?.Invoke();
return await this.Repository.DeleteAsync(this as TEntity) == 1; return await Repository.DeleteAsync(this as TEntity) == 1;
} }
/// <summary> /// <summary>
/// To recover deleted data <br />
/// 恢复删除的数据 /// 恢复删除的数据
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public virtual Task<bool> RestoreAsync() => this.UpdateIsDeletedAsync(false); public virtual Task<bool> RestoreAsync() => UpdateIsDeletedAsync(false);
/// <summary> /// <summary>
/// To update data <br />
/// 更新数据 /// 更新数据
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
async public virtual Task<bool> UpdateAsync() public virtual async Task<bool> UpdateAsync()
{ {
this.UpdateTime = DateTime.Now; UpdateTime = DateTime.Now;
if (this.Repository == null) if (Repository is null)
{
return await Orm.Update<TEntity>() return await Orm.Update<TEntity>()
.WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction()) .WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction())
.SetSource(this as TEntity).ExecuteAffrowsAsync() == 1; .SetSource(this as TEntity).ExecuteAffrowsAsync() == 1;
}
this.Repository.UnitOfWork = _resolveUow?.Invoke(); Repository.UnitOfWork = _resolveUow?.Invoke();
return await this.Repository.UpdateAsync(this as TEntity) == 1; return await Repository.UpdateAsync(this as TEntity) == 1;
} }
/// <summary> /// <summary>
/// To insert data <br />
/// 插入数据 /// 插入数据
/// </summary> /// </summary>
public virtual Task<TEntity> InsertAsync() public virtual Task<TEntity> InsertAsync()
{ {
this.CreateTime = DateTime.Now; CreateTime = DateTime.Now;
if (this.Repository == null) Repository ??= Orm.GetRepository<TEntity>();
this.Repository = Orm.GetRepository<TEntity>(); Repository.UnitOfWork = _resolveUow?.Invoke();
return Repository.InsertAsync(this as TEntity);
this.Repository.UnitOfWork = _resolveUow?.Invoke();
return this.Repository.InsertAsync(this as TEntity);
} }
/// <summary> /// <summary>
/// To insert or update data <br />
/// 更新或插入 /// 更新或插入
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public virtual Task<TEntity> SaveAsync() public virtual Task<TEntity> SaveAsync()
{ {
this.UpdateTime = DateTime.Now; UpdateTime = DateTime.Now;
if (this.Repository == null) Repository ??= Orm.GetRepository<TEntity>();
this.Repository = Orm.GetRepository<TEntity>(); Repository.UnitOfWork = _resolveUow?.Invoke();
return Repository.InsertOrUpdateAsync(this as TEntity);
this.Repository.UnitOfWork = _resolveUow?.Invoke();
return this.Repository.InsertOrUpdateAsync(this as TEntity);
} }
/// <summary> /// <summary>
/// To completely save the navigation properties of the entity in the form of sub-tables. <br />
/// 【完整】保存导航属性,子表 /// 【完整】保存导航属性,子表
/// </summary> /// </summary>
/// <param name="navigatePropertyName">导航属性名</param> /// <param name="navigatePropertyName">Navigation property name</param>
public virtual Task SaveManyAsync(string navigatePropertyName) public virtual Task SaveManyAsync(string navigatePropertyName)
{ {
if (this.Repository == null) Repository ??= Orm.GetRepository<TEntity>();
this.Repository = Orm.GetRepository<TEntity>(); Repository.UnitOfWork = _resolveUow?.Invoke();
return Repository.SaveManyAsync(this as TEntity, navigatePropertyName);
this.Repository.UnitOfWork = _resolveUow?.Invoke();
return this.Repository.SaveManyAsync(this as TEntity, navigatePropertyName);
} }
#endif #endif
} }

View File

@ -1,44 +1,53 @@
 using FreeSql.DataAnnotations;
using FreeSql.DataAnnotations;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Threading; using System.Threading;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable InconsistentlySynchronizedField
namespace FreeSql namespace FreeSql
{ {
/// <summary> /// <summary>
/// Entity base class, including CreateTime/UpdateTime/IsDeleted.
/// <para></para>
/// 包括 CreateTime/UpdateTime/IsDeleted 的实体基类 /// 包括 CreateTime/UpdateTime/IsDeleted 的实体基类
/// </summary> /// </summary>
[Table(DisableSyncStructure = true)] [Table(DisableSyncStructure = true)]
public abstract class BaseEntity public abstract class BaseEntity
{ {
internal static IFreeSql _ormPriv; internal static IFreeSql _ormPriv;
private const string ErrorMessageTemplate = @"使用前请初始化:
BaseEntity.Initialization(new FreeSqlBuilder()
.UseAutoSyncStructure(true)
.UseConnectionString(DataType.Sqlite, ""data source=test.db;max pool size=5"")
.Build());";
/// <summary> /// <summary>
/// 全局 IFreeSql orm 对象 /// Global IFreeSql ORM Object <br />
/// 全局 IFreeSql ORM 对象
/// </summary> /// </summary>
public static IFreeSql Orm => _ormPriv ?? throw new Exception(@"使用前请初始化 BaseEntity.Initialization(new FreeSqlBuilder() public static IFreeSql Orm => _ormPriv ?? throw new Exception(ErrorMessageTemplate);
.UseAutoSyncStructure(true)
.UseConnectionString(DataType.Sqlite, ""data source=test.db;max pool size=5"")
.Build());");
internal static Func<IUnitOfWork> _resolveUow; internal static Func<IUnitOfWork> _resolveUow;
/// <summary> /// <summary>
/// 初始化BaseEntity /// To initialize the BaseEntity <br />
/// BaseEntity.Initialization(new FreeSqlBuilder() /// 初始化 BaseEntity
/// <para></para> /// <para></para>
/// .UseAutoSyncStructure(true) /// BaseEntity.Initialization( <br />
/// <para></para> /// new FreeSqlBuilder() <br />
/// .UseConnectionString(DataType.Sqlite, "data source=test.db;max pool size=5") /// .UseAutoSyncStructure(true) <br />
/// <para></para> /// .UseConnectionString(DataType.Sqlite, "data source=test.db;max pool size=5") <br />
/// .Build()); /// .Build());
/// </summary> /// </summary>
/// <param name="fsql">IFreeSql orm 对象</param> /// <param name="fsql">IFreeSql ORM Object</param>
/// <param name="resolveUow">工作单元(事务)委托,如果不使用事务请传 null<para></para>解释由于AsyncLocal平台兼容不好所以交给外部管理</param> /// <param name="resolveUow">工作单元(事务)委托,如果不使用事务请传 null<para></para>解释由于AsyncLocal平台兼容不好所以交给外部管理</param>
public static void Initialization(IFreeSql fsql, Func<IUnitOfWork> resolveUow) public static void Initialization(IFreeSql fsql, Func<IUnitOfWork> resolveUow)
{ {
@ -52,6 +61,7 @@ namespace FreeSql
_ormPriv.CodeFirst.ConfigEntity(cei.EntityType, cei.Fluent); _ormPriv.CodeFirst.ConfigEntity(cei.EntityType, cei.Fluent);
} }
} }
_resolveUow = resolveUow; _resolveUow = resolveUow;
} }
@ -60,13 +70,15 @@ namespace FreeSql
public Type EntityType; public Type EntityType;
public Action<TableFluent> Fluent; public Action<TableFluent> Fluent;
} }
static ConcurrentQueue<ConfigEntityInfo> _configEntityQueues = new ConcurrentQueue<ConfigEntityInfo>();
static object _configEntityLock = new object(); static readonly ConcurrentQueue<ConfigEntityInfo> _configEntityQueues = new();
static readonly object _configEntityLock = new();
internal static void ConfigEntity(Type entityType, Action<TableFluent> fluent) internal static void ConfigEntity(Type entityType, Action<TableFluent> fluent)
{ {
lock (_configEntityLock) lock (_configEntityLock)
{ {
if (_ormPriv == null) if (_ormPriv is null)
_configEntityQueues.Enqueue(new ConfigEntityInfo { EntityType = entityType, Fluent = fluent }); _configEntityQueues.Enqueue(new ConfigEntityInfo { EntityType = entityType, Fluent = fluent });
else else
_ormPriv.CodeFirst.ConfigEntity(entityType, fluent); _ormPriv.CodeFirst.ConfigEntity(entityType, fluent);
@ -74,31 +86,45 @@ namespace FreeSql
} }
/// <summary> /// <summary>
/// Created time <br />
/// 创建时间 /// 创建时间
/// </summary> /// </summary>
[Column(Position = -4)] [Column(Position = -4)]
public virtual DateTime CreateTime { get; set; } = DateTime.Now; public virtual DateTime CreateTime { get; set; } = DateTime.Now;
/// <summary> /// <summary>
/// Updated time <br />
/// 更新时间 /// 更新时间
/// </summary> /// </summary>
[Column(Position = -3)] [Column(Position = -3)]
public virtual DateTime UpdateTime { get; set; } public virtual DateTime UpdateTime { get; set; }
/// <summary> /// <summary>
/// Logical Delete <br />
/// 逻辑删除 /// 逻辑删除
/// </summary> /// </summary>
[Column(Position = -2)] [Column(Position = -2)]
public virtual bool IsDeleted { get; set; } public virtual bool IsDeleted { get; set; }
/// <summary> /// <summary>
/// Sort <br />
/// 排序 /// 排序
/// </summary> /// </summary>
[Column(Position = -1)] [Column(Position = -1)]
public virtual int Sort { get; set; } public virtual int Sort { get; set; }
} }
/// <summary>
/// A readonly entity base class, including CreateTime/UpdateTime/IsDeleted.
/// <para></para>
/// 包括 CreateTime/UpdateTime/IsDeleted 的只读实体基类
/// </summary>
/// <typeparam name="TEntity"></typeparam>
[Table(DisableSyncStructure = true)] [Table(DisableSyncStructure = true)]
public abstract class BaseEntityReadOnly<TEntity> : BaseEntity where TEntity : class public abstract class BaseEntityReadOnly<TEntity> : BaseEntity where TEntity : class
{ {
/// <summary> /// <summary>
/// To query data <br />
/// 查询数据 /// 查询数据
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
@ -107,68 +133,92 @@ namespace FreeSql
get get
{ {
var select = Orm.Select<TEntity>() var select = Orm.Select<TEntity>()
.TrackToList(TrackToList) //自动为每个元素 Attach .TrackToList(TrackToList) //自动为每个元素 Attach
.WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction(false)); .WithTransaction(_resolveUow?.Invoke()?.GetOrBeginTransaction(false));
return select.WhereCascade(a => (a as BaseEntity).IsDeleted == false); return select.WhereCascade(a => (a as BaseEntity).IsDeleted == false);
} }
} }
static void TrackToList(object list) static void TrackToList(object list)
{ {
if (list == null) return; if (list is null)
var ls = list as IList<TEntity>; return;
if (ls == null)
if (list is not IList<TEntity> ls)
{ {
var ie = list as IEnumerable; if (list is not IEnumerable ie)
if (ie == null) return; return;
var isFirst = true; var isFirst = true;
IBaseRepository<TEntity> berepo = null; IBaseRepository<TEntity> baseRepo = null;
foreach (var item in ie) foreach (var item in ie)
{ {
if (item == null) return; if (item is null)
{
return;
}
if (isFirst) if (isFirst)
{ {
isFirst = false; isFirst = false;
var itemType = item.GetType(); var itemType = item.GetType();
if (itemType == typeof(object)) return; if (itemType == typeof(object)) return;
if (itemType.FullName.Contains("FreeSqlLazyEntity__")) itemType = itemType.BaseType; if (itemType.FullName!.Contains("FreeSqlLazyEntity__")) itemType = itemType.BaseType;
if (Orm.CodeFirst.GetTableByEntity(itemType)?.Primarys.Any() != true) return; if (Orm.CodeFirst.GetTableByEntity(itemType)?.Primarys.Any() != true) return;
if (item is BaseEntity<TEntity> == false) return; if (item is not BaseEntity<TEntity>) return;
} }
var beitem = item as BaseEntity<TEntity>;
if (beitem != null) if (item is BaseEntity<TEntity> entity)
{ {
if (berepo == null) berepo = Orm.GetRepository<TEntity>(); baseRepo ??= Orm.GetRepository<TEntity>();
beitem.Repository = berepo; entity.Repository = baseRepo;
beitem.Attach(); entity.Attach();
} }
} }
return; return;
} }
if (ls.Any() == false) return;
if (ls.FirstOrDefault() is BaseEntity<TEntity> == false) return; if (ls.Any() == false)
if (Orm.CodeFirst.GetTableByEntity(typeof(TEntity))?.Primarys.Any() != true) return; return;
if (ls.FirstOrDefault() is not BaseEntity<TEntity>)
return;
if (Orm.CodeFirst.GetTableByEntity(typeof(TEntity))?.Primarys.Any() != true)
return;
IBaseRepository<TEntity> repo = null; IBaseRepository<TEntity> repo = null;
foreach (var item in ls) foreach (var item in ls)
{ {
var beitem = item as BaseEntity<TEntity>; if (item is BaseEntity<TEntity> entity)
if (beitem != null)
{ {
if (repo == null) repo = Orm.GetRepository<TEntity>(); repo ??= Orm.GetRepository<TEntity>();
beitem.Repository = repo; entity.Repository = repo;
beitem.Attach(); entity.Attach();
} }
} }
} }
/// <summary> /// <summary>
/// 查询条件Where(a => a.Id > 10)支持导航对象查询Where(a => a.Author.Email == "2881099@qq.com") /// Query conditions <br />
/// 查询条件Where(a => a.Id> 10)
/// <para></para>
/// Support navigation object query <br />
/// 支持导航对象查询Where(a => a.Author.Email == "2881099@qq.com")
/// </summary> /// </summary>
/// <param name="exp">lambda表达式</param> /// <param name="exp">lambda表达式</param>
/// <returns></returns> /// <returns></returns>
public static ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => Select.Where(exp); public static ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => Select.Where(exp);
/// <summary> /// <summary>
/// 查询条件Where(true, a => a.Id > 10)支导航对象查询Where(true, a => a.Author.Email == "2881099@qq.com") /// Query conditions <br />
/// 查询条件Where(true, a => a.Id > 10)
/// <para></para>
/// Support navigation object query <br />
/// 支导航对象查询Where(true, a => a.Author.Email == "2881099@qq.com")
/// </summary> /// </summary>
/// <param name="condition">true 时生效</param> /// <param name="condition">true 时生效</param>
/// <param name="exp">lambda表达式</param> /// <param name="exp">lambda表达式</param>
@ -176,20 +226,20 @@ namespace FreeSql
public static ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => Select.WhereIf(condition, exp); public static ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => Select.WhereIf(condition, exp);
/// <summary> /// <summary>
/// Repository object. <br />
/// 仓储对象 /// 仓储对象
/// </summary> /// </summary>
protected IBaseRepository<TEntity> Repository { get; set; } protected IBaseRepository<TEntity> Repository { get; set; }
/// <summary> /// <summary>
/// 附加实体,在更新数据时,只更新变化的部分 /// To Attach entities. When updating data, only the changed part is updated. <br />
/// 附加实体。在更新数据时,只更新变化的部分
/// </summary> /// </summary>
public TEntity Attach() public TEntity Attach()
{ {
if (this.Repository == null) Repository ??= Orm.GetRepository<TEntity>();
this.Repository = Orm.GetRepository<TEntity>();
var item = this as TEntity; var item = this as TEntity;
this.Repository.Attach(item); Repository.Attach(item);
return item; return item;
} }
} }

View File

@ -6,8 +6,8 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors>FreeSql;ncc;YeXiangQin</Authors> <Authors>FreeSql;ncc;YeXiangQin</Authors>
<Description>BaseEntity 是一种极简单的 CodeFirst 开发方式特别对单表或多表CRUD利用继承节省了每个实体类的重复属性创建时间、ID等字段软件删除等功能进行 crud 操作时不必时常考虑仓储的使用.</Description> <Description>BaseEntity 是一种极简单的 CodeFirst 开发方式特别对单表或多表CRUD利用继承节省了每个实体类的重复属性创建时间、ID等字段软件删除等功能进行 crud 操作时不必时常考虑仓储的使用.</Description>
<PackageProjectUrl>https://github.com/2881099/FreeSql/tree/master/Extensions/FreeSql.Extensions.BaseEntity</PackageProjectUrl> <PackageProjectUrl>https://github.com/dotnetcore/FreeSql/tree/master/Extensions/FreeSql.Extensions.BaseEntity</PackageProjectUrl>
<RepositoryUrl>https://github.com/2881099/FreeSql/tree/master/Extensions/FreeSql.Extensions.BaseEntity</RepositoryUrl> <RepositoryUrl>https://github.com/dotnetcore/FreeSql/tree/master/Extensions/FreeSql.Extensions.BaseEntity</RepositoryUrl>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>
<PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageTags>FreeSql;ORM;BaseEntity</PackageTags> <PackageTags>FreeSql;ORM;BaseEntity</PackageTags>
@ -19,6 +19,7 @@
<SignAssembly>true</SignAssembly> <SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile> <AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
<DelaySign>false</DelaySign> <DelaySign>false</DelaySign>
<LangVersion>latest</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>