mirror of
https://github.com/nsnail/FreeSql.git
synced 2025-04-22 10:42:52 +08:00
BaseEntity + 异步事务测试
This commit is contained in:
parent
762bd0df2b
commit
f9600d6c76
@ -2,8 +2,10 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.Linq.Expressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
[Table(DisableSyncStructure = true)]
|
||||
public abstract class BaseEntity
|
||||
@ -13,7 +15,7 @@ public abstract class BaseEntity
|
||||
var orm = new FreeSqlBuilder()
|
||||
.UseAutoSyncStructure(true)
|
||||
.UseNoneCommandParameter(true)
|
||||
.UseConnectionString(DataType.Sqlite, "data source=test.db;max pool size=2")
|
||||
.UseConnectionString(DataType.Sqlite, "data source=test.db;max pool size=5")
|
||||
//.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=2")
|
||||
//.UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=2")
|
||||
//.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=2")
|
||||
@ -36,71 +38,108 @@ public abstract class BaseEntity
|
||||
/// 逻辑删除
|
||||
/// </summary>
|
||||
public bool IsDeleted { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 开启工作单元事务
|
||||
/// </summary>
|
||||
/// <param name="level"></param>
|
||||
/// <returns></returns>
|
||||
public static IUnitOfWork Begin() => Begin(null);
|
||||
public static IUnitOfWork Begin(IsolationLevel? level)
|
||||
{
|
||||
var uow = new BaseEntityUnitOfWork(Orm);
|
||||
uow.IsolationLevel = level;
|
||||
return uow;
|
||||
}
|
||||
protected static IUnitOfWork CurrentUow => BaseEntityUnitOfWork._asyncUow.Value;
|
||||
}
|
||||
|
||||
[Table(DisableSyncStructure = true)]
|
||||
public abstract class BaseEntity<TEntity> : BaseEntity where TEntity : class
|
||||
{
|
||||
public static ISelect<TEntity> Select => Orm.Select<TEntity>().WhereCascade(a => (a as BaseEntity<TEntity>).IsDeleted == false);
|
||||
public static ISelect<TEntity> Select => Orm.Select<TEntity>()
|
||||
.WithTransaction(CurrentUow?.GetOrBeginTransaction(false))
|
||||
.WhereCascade(a => (a as BaseEntity<TEntity>).IsDeleted == false);
|
||||
public static ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => Select.Where(exp);
|
||||
public static ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => Select.WhereIf(condition, exp);
|
||||
|
||||
[JsonIgnore]
|
||||
protected IBaseRepository<TEntity> Repository { get; set; }
|
||||
|
||||
bool UpdateIsDeleted(bool value)
|
||||
async Task<bool> UpdateIsDeleted(bool value)
|
||||
{
|
||||
if (this.Repository == null)
|
||||
return Orm.Update<TEntity>(this as TEntity).Set(a => (a as BaseEntity<TEntity>).IsDeleted, this.IsDeleted = value).ExecuteAffrows() == 1;
|
||||
return await Orm.Update<TEntity>(this as TEntity)
|
||||
.WithTransaction(CurrentUow?.GetOrBeginTransaction())
|
||||
.Set(a => (a as BaseEntity<TEntity>).IsDeleted, this.IsDeleted = value).ExecuteAffrowsAsync() == 1;
|
||||
|
||||
this.IsDeleted = value;
|
||||
return this.Repository.Update(this as TEntity) == 1;
|
||||
this.Repository.UnitOfWork = CurrentUow;
|
||||
return await this.Repository.UpdateAsync(this as TEntity) == 1;
|
||||
}
|
||||
/// <summary>
|
||||
/// 删除数据
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual bool Delete() => this.UpdateIsDeleted(true);
|
||||
public virtual Task<bool> Delete() => this.UpdateIsDeleted(true);
|
||||
/// <summary>
|
||||
/// 恢复删除的数据
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual bool Restore() => this.UpdateIsDeleted(false);
|
||||
public virtual Task<bool> Restore() => this.UpdateIsDeleted(false);
|
||||
|
||||
/// <summary>
|
||||
/// 附加实体,在更新数据时,只更新变化的部分
|
||||
/// </summary>
|
||||
public void Attach()
|
||||
public TEntity Attach()
|
||||
{
|
||||
if (this.Repository == null) this.Repository = Orm.GetRepository<TEntity>();
|
||||
this.Repository.Attach(this as TEntity);
|
||||
if (this.Repository == null)
|
||||
this.Repository = Orm.GetRepository<TEntity>();
|
||||
|
||||
var item = this as TEntity;
|
||||
this.Repository.Attach(item);
|
||||
return item;
|
||||
}
|
||||
/// <summary>
|
||||
/// 更新数据
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual bool Update()
|
||||
async public virtual Task<bool> Update()
|
||||
{
|
||||
this.UpdateTime = DateTime.Now;
|
||||
if (this.Repository == null)
|
||||
return Orm.Update<TEntity>().SetSource(this as TEntity).ExecuteAffrows() == 1;
|
||||
return this.Repository.Update(this as TEntity) == 1;
|
||||
return await Orm.Update<TEntity>()
|
||||
.WithTransaction(CurrentUow?.GetOrBeginTransaction())
|
||||
.SetSource(this as TEntity).ExecuteAffrowsAsync() == 1;
|
||||
|
||||
this.Repository.UnitOfWork = CurrentUow;
|
||||
return await this.Repository.UpdateAsync(this as TEntity) == 1;
|
||||
}
|
||||
/// <summary>
|
||||
/// 插入数据
|
||||
/// </summary>
|
||||
public virtual void Insert()
|
||||
async public virtual Task Insert()
|
||||
{
|
||||
if (this.Repository == null) this.Repository = Orm.GetRepository<TEntity>();
|
||||
this.Repository.Insert(this as TEntity);
|
||||
this.CreateTime = DateTime.Now;
|
||||
if (this.Repository == null)
|
||||
this.Repository = Orm.GetRepository<TEntity>();
|
||||
|
||||
this.Repository.UnitOfWork = CurrentUow;
|
||||
await this.Repository.InsertAsync(this as TEntity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新或插入
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public virtual void Save()
|
||||
async public virtual Task Save()
|
||||
{
|
||||
if (this.Repository == null) this.Repository = Orm.GetRepository<TEntity>();
|
||||
this.Repository.InsertOrUpdate(this as TEntity);
|
||||
this.UpdateTime = DateTime.Now;
|
||||
if (this.Repository == null)
|
||||
this.Repository = Orm.GetRepository<TEntity>();
|
||||
|
||||
this.Repository.UnitOfWork = CurrentUow;
|
||||
await this.Repository.InsertOrUpdateAsync(this as TEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@ -125,43 +164,10 @@ public abstract class BaseEntity<TEntity, TKey> : BaseEntity<TEntity> where TEnt
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <returns></returns>
|
||||
public static TEntity Find(TKey id)
|
||||
async public static Task<TEntity> Find(TKey id)
|
||||
{
|
||||
var item = Select.WhereDynamic(id).First();
|
||||
var item = await Select.WhereDynamic(id).FirstAsync();
|
||||
(item as BaseEntity<TEntity>)?.Attach();
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
[Table(DisableSyncStructure = true)]
|
||||
public abstract class BaseEntity<TEntity, TKey1, TKey2> : BaseEntity<TEntity> where TEntity : class
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 主键1
|
||||
/// </summary>
|
||||
[Column(IsPrimary = true)]
|
||||
public virtual TKey1 PkId1 { get; set; }
|
||||
/// <summary>
|
||||
/// 主键2
|
||||
/// </summary>
|
||||
[Column(IsPrimary = true)]
|
||||
public virtual TKey2 PkId2 { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 根据主键值获取数据
|
||||
/// </summary>
|
||||
/// <param name="pkid1">主键1</param>
|
||||
/// <param name="pkid2">主键2</param>
|
||||
/// <returns></returns>
|
||||
public static TEntity Find(TKey1 pkid1, TKey1 pkid2)
|
||||
{
|
||||
var item = Select.WhereDynamic(new
|
||||
{
|
||||
PkId1 = pkid1,
|
||||
PkId2 = pkid2
|
||||
}).First();
|
||||
(item as BaseEntity<TEntity>).Attach();
|
||||
return item;
|
||||
}
|
||||
}
|
124
Examples/base_entity/BaseEntityUnitOfWork.cs
Normal file
124
Examples/base_entity/BaseEntityUnitOfWork.cs
Normal file
@ -0,0 +1,124 @@
|
||||
using FreeSql;
|
||||
using SafeObjectPool;
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Threading;
|
||||
|
||||
class BaseEntityUnitOfWork : IUnitOfWork
|
||||
{
|
||||
internal readonly static AsyncLocal<IUnitOfWork> _asyncUow = new AsyncLocal<IUnitOfWork>();
|
||||
|
||||
protected IFreeSql _fsql;
|
||||
protected Object<DbConnection> _conn;
|
||||
protected DbTransaction _tran;
|
||||
|
||||
public BaseEntityUnitOfWork(IFreeSql fsql)
|
||||
{
|
||||
_fsql = fsql;
|
||||
_asyncUow.Value = this;
|
||||
}
|
||||
|
||||
void ReturnObject()
|
||||
{
|
||||
_fsql.Ado.MasterPool.Return(_conn);
|
||||
_tran = null;
|
||||
_conn = null;
|
||||
_asyncUow.Value = null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用工作单元
|
||||
/// </summary>
|
||||
public bool Enable { get; private set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 禁用工作单元
|
||||
/// <exception cref="Exception"></exception>
|
||||
/// <para></para>
|
||||
/// 若已开启事务(已有Insert/Update/Delete操作),调用此方法将发生异常,建议在执行逻辑前调用
|
||||
/// </summary>
|
||||
public void Close()
|
||||
{
|
||||
if (_tran != null)
|
||||
throw new Exception("已开启事务,不能禁用工作单元");
|
||||
|
||||
Enable = false;
|
||||
}
|
||||
|
||||
public void Open() =>
|
||||
Enable = true;
|
||||
|
||||
public IsolationLevel? IsolationLevel { get; set; }
|
||||
|
||||
public DbTransaction GetOrBeginTransaction(bool isCreate = true)
|
||||
{
|
||||
|
||||
if (_tran != null) return _tran;
|
||||
if (isCreate == false) return null;
|
||||
if (!Enable) return null;
|
||||
if (_conn != null) _fsql.Ado.MasterPool.Return(_conn);
|
||||
|
||||
_conn = _fsql.Ado.MasterPool.Get();
|
||||
try
|
||||
{
|
||||
_tran = IsolationLevel == null ?
|
||||
_conn.Value.BeginTransaction() :
|
||||
_conn.Value.BeginTransaction(IsolationLevel.Value);
|
||||
}
|
||||
catch
|
||||
{
|
||||
ReturnObject();
|
||||
throw;
|
||||
}
|
||||
return _tran;
|
||||
}
|
||||
|
||||
public void Commit()
|
||||
{
|
||||
if (_tran != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
_tran.Commit();
|
||||
}
|
||||
finally
|
||||
{
|
||||
ReturnObject();
|
||||
}
|
||||
}
|
||||
}
|
||||
public void Rollback()
|
||||
{
|
||||
if (_tran != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
_tran.Rollback();
|
||||
}
|
||||
finally
|
||||
{
|
||||
ReturnObject();
|
||||
}
|
||||
}
|
||||
}
|
||||
~BaseEntityUnitOfWork()
|
||||
{
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose()
|
||||
{
|
||||
if (_isdisposed) return;
|
||||
_isdisposed = true;
|
||||
try
|
||||
{
|
||||
this.Rollback();
|
||||
}
|
||||
finally
|
||||
{
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
@ -10,8 +10,6 @@ public class UserGroup : BaseEntity<UserGroup, int>
|
||||
public string GroupName { get; set; }
|
||||
|
||||
public List<User1> User1s { get; set; }
|
||||
|
||||
public List<User2> User2s { get; set; }
|
||||
}
|
||||
|
||||
public class Role : BaseEntity<Role, string>
|
||||
@ -54,38 +52,3 @@ public class User1 : BaseEntity<User1, Guid>
|
||||
/// </summary>
|
||||
public string Description { get; set; }
|
||||
}
|
||||
|
||||
public class User2 : BaseEntity<User2, Guid, int>
|
||||
{
|
||||
static User2()
|
||||
{
|
||||
User2.Orm.CodeFirst.ConfigEntity<User2>(t =>
|
||||
{
|
||||
t.Property(a => a.PkId1).Name("UserId");
|
||||
t.Property(a => a.PkId2).Name("Index");
|
||||
});
|
||||
}
|
||||
|
||||
public int GroupId { get; set; }
|
||||
public UserGroup Group { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 登陆名
|
||||
/// </summary>
|
||||
public string Username { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 昵称
|
||||
/// </summary>
|
||||
public string Nickname { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 头像
|
||||
/// </summary>
|
||||
public string Avatar { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 描述
|
||||
/// </summary>
|
||||
public string Description { get; set; }
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace base_entity
|
||||
{
|
||||
@ -6,75 +7,71 @@ namespace base_entity
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Task.Run(async () =>
|
||||
{
|
||||
using (var uow = BaseEntity.Begin())
|
||||
{
|
||||
var itt = await UserGroup.Find(1);
|
||||
}
|
||||
|
||||
var ug1 = new UserGroup();
|
||||
ug1.GroupName = "分组一";
|
||||
ug1.Insert();
|
||||
await ug1.Insert();
|
||||
|
||||
var ug2 = new UserGroup();
|
||||
ug2.GroupName = "分组二";
|
||||
ug2.Insert();
|
||||
await ug2.Insert();
|
||||
|
||||
var u1 = new User1();
|
||||
var u2 = new User2();
|
||||
|
||||
u1.GroupId = ug1.Id;
|
||||
u1.Save();
|
||||
await u1.Save();
|
||||
|
||||
u2.GroupId = ug2.Id;
|
||||
u2.Save();
|
||||
|
||||
u1.Delete();
|
||||
u1.Restore();
|
||||
await u1.Delete();
|
||||
await u1.Restore();
|
||||
|
||||
u1.Nickname = "x1";
|
||||
u1.Update();
|
||||
await u1.Update();
|
||||
|
||||
u2.Delete();
|
||||
u2.Restore();
|
||||
|
||||
u2.Username = "x2";
|
||||
u2.Update();
|
||||
|
||||
var u11 = User1.Find(u1.Id);
|
||||
var u11 = await User1.Find(u1.Id);
|
||||
u11.Description = "备注";
|
||||
u11.Save();
|
||||
await u11.Save();
|
||||
|
||||
u11.Delete();
|
||||
await u11.Delete();
|
||||
|
||||
var u11null = User1.Find(u1.Id);
|
||||
|
||||
var u11s = User1.Where(a => a.Group.Id == ug1.Id).Limit(10).ToList();
|
||||
var u22s = User2.Where(a => a.Group.Id == ug2.Id).Limit(10).ToList();
|
||||
|
||||
var u11s2 = User1.Select.LeftJoin<UserGroup>((a, b) => a.GroupId == b.Id).Limit(10).ToList();
|
||||
var u22s2 = User2.Select.LeftJoin<UserGroup>((a, b) => a.GroupId == b.Id).Limit(10).ToList();
|
||||
|
||||
var ug1s = UserGroup.Select
|
||||
.IncludeMany(a => a.User1s)
|
||||
.IncludeMany(a => a.User2s)
|
||||
.Limit(10).ToList();
|
||||
|
||||
var ug1s2 = UserGroup.Select.Where(a => a.User1s.AsSelect().Any(b => b.Nickname == "x1")).Limit(10).ToList();
|
||||
|
||||
var r1 = new Role();
|
||||
r1.Id = "管理员";
|
||||
r1.Save();
|
||||
await r1.Save();
|
||||
|
||||
var r2 = new Role();
|
||||
r2.Id = "超级会员";
|
||||
r2.Save();
|
||||
await r2.Save();
|
||||
|
||||
var ru1 = new RoleUser1();
|
||||
ru1.User1Id = u1.Id;
|
||||
ru1.RoleId = r1.Id;
|
||||
ru1.Save();
|
||||
await ru1.Save();
|
||||
|
||||
ru1.RoleId = r2.Id;
|
||||
ru1.Save();
|
||||
await ru1.Save();
|
||||
|
||||
var u1roles = User1.Select.IncludeMany(a => a.Roles).ToList();
|
||||
var u1roles2 = User1.Select.Where(a => a.Roles.AsSelect().Any(b => b.Id == "xx")).ToList();
|
||||
|
||||
}).Wait();
|
||||
|
||||
Console.WriteLine("按任意键结束。。。");
|
||||
Console.ReadKey();
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user