mirror of
https://github.com/nsnail/FreeSql.git
synced 2025-06-18 20:08:15 +08:00
## v0.3.27
- 增加 行级锁功能,适用修改实体; - 增加 FreeSql.Repository 默认依赖注入的方式,同时保留原有 Autofac; - 优化 FreeSql.Repository Insert 逻辑,参考了 FreeSql.DbContext; - 优化 FreeSql.IUpdate 参照 IInsert 对大批量更新,拆分执行; - 修复 FreeSql.IInsert ClearData 重复利用的 bug(使用 IgnoreColumns 进行大批量插入时会发生);
This commit is contained in:
@ -1,8 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace FreeSql {
|
||||
public class VersionAttribute : Attribute {
|
||||
}
|
||||
}
|
@ -42,8 +42,15 @@ namespace FreeSql {
|
||||
|
||||
}
|
||||
|
||||
|
||||
Dictionary<Type, object> _dicSet = new Dictionary<Type, object>();
|
||||
public DbSet<TEntity> Set<TEntity>() where TEntity : class => this.Set(typeof(TEntity)) as DbSet<TEntity>;
|
||||
public object Set(Type entityType) => Activator.CreateInstance(typeof(BaseDbSet<>).MakeGenericType(entityType), this);
|
||||
public object Set(Type entityType) {
|
||||
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
|
||||
var sd = Activator.CreateInstance(typeof(BaseDbSet<>).MakeGenericType(entityType), this);
|
||||
_dicSet.Add(entityType, sd);
|
||||
return sd;
|
||||
}
|
||||
|
||||
protected Dictionary<string, object> AllSets { get; } = new Dictionary<string, object>();
|
||||
|
||||
@ -92,6 +99,7 @@ namespace FreeSql {
|
||||
}
|
||||
}
|
||||
void Rollback() {
|
||||
_actions.Clear();
|
||||
if (_tran != null) {
|
||||
try {
|
||||
_tran.Rollback();
|
||||
|
@ -1,35 +1,63 @@
|
||||
using FreeSql.Internal.Model;
|
||||
using FreeSql.Extensions.EntityUtil;
|
||||
using FreeSql.Internal.Model;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reflection;
|
||||
using FreeSql.Extensions;
|
||||
|
||||
namespace FreeSql {
|
||||
|
||||
internal class BaseDbSet<TEntity> : DbSet<TEntity> where TEntity : class {
|
||||
|
||||
public BaseDbSet(DbContext ctx) {
|
||||
_ctx = ctx;
|
||||
_fsql = ctx._fsql;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract partial class DbSet<TEntity> where TEntity : class {
|
||||
|
||||
internal DbContext _ctx;
|
||||
IFreeSql _fsql => _ctx._fsql;
|
||||
internal IFreeSql _fsql;
|
||||
|
||||
ISelect<TEntity> OrmSelect(object dywhere) {
|
||||
_ctx.ExecCommand(); //查询前先提交,否则会出脏读
|
||||
return _fsql.Select<TEntity>(dywhere).WithTransaction(_ctx.GetOrBeginTransaction(false)).TrackToList(TrackToList);
|
||||
internal ISelect<TEntity> OrmSelect(object dywhere) {
|
||||
ExecuteCommand(); //查询前先提交,否则会出脏读
|
||||
return _fsql.Select<TEntity>(dywhere).WithTransaction(_ctx?.GetOrBeginTransaction(false)).TrackToList(TrackToList);
|
||||
}
|
||||
|
||||
IInsert<TEntity> OrmInsert() => _fsql.Insert<TEntity>().WithTransaction(_ctx.GetOrBeginTransaction());
|
||||
IInsert<TEntity> OrmInsert(TEntity data) => _fsql.Insert<TEntity>(data).WithTransaction(_ctx.GetOrBeginTransaction());
|
||||
IInsert<TEntity> OrmInsert(TEntity[] data) => _fsql.Insert<TEntity>(data).WithTransaction(_ctx.GetOrBeginTransaction());
|
||||
IInsert<TEntity> OrmInsert(IEnumerable<TEntity> data) => _fsql.Insert<TEntity>(data).WithTransaction(_ctx.GetOrBeginTransaction());
|
||||
internal virtual IInsert<TEntity> OrmInsert() => _fsql.Insert<TEntity>().WithTransaction(_ctx?.GetOrBeginTransaction());
|
||||
internal virtual IInsert<TEntity> OrmInsert(TEntity data) => _fsql.Insert<TEntity>(data).WithTransaction(_ctx?.GetOrBeginTransaction());
|
||||
internal virtual IInsert<TEntity> OrmInsert(TEntity[] data) => _fsql.Insert<TEntity>(data).WithTransaction(_ctx?.GetOrBeginTransaction());
|
||||
internal virtual IInsert<TEntity> OrmInsert(IEnumerable<TEntity> data) => _fsql.Insert<TEntity>(data).WithTransaction(_ctx?.GetOrBeginTransaction());
|
||||
|
||||
IUpdate<TEntity> OrmUpdate(object dywhere) => _fsql.Update<TEntity>(dywhere).WithTransaction(_ctx.GetOrBeginTransaction());
|
||||
IDelete<TEntity> OrmDelete(object dywhere) => _fsql.Delete<TEntity>(dywhere).WithTransaction(_ctx.GetOrBeginTransaction());
|
||||
internal virtual IUpdate<TEntity> OrmUpdate(object dywhere) => _fsql.Update<TEntity>(dywhere).WithTransaction(_ctx?.GetOrBeginTransaction());
|
||||
internal virtual IDelete<TEntity> OrmDelete(object dywhere) => _fsql.Delete<TEntity>(dywhere).WithTransaction(_ctx?.GetOrBeginTransaction());
|
||||
|
||||
internal void EnqueueAction(DbContext.ExecCommandInfoType actionType, object dbSet, Type stateType, object state) {
|
||||
_ctx?.EnqueueAction(actionType, dbSet, stateType, state);
|
||||
}
|
||||
internal void ExecuteCommand() {
|
||||
_ctx?.ExecCommand();
|
||||
}
|
||||
internal void IncrAffrows(long affrows) {
|
||||
if (_ctx != null)
|
||||
_ctx._affrows += affrows;
|
||||
}
|
||||
internal void TrackToList(object list) {
|
||||
if (list == null) return;
|
||||
var ls = list as IList<TEntity>;
|
||||
if (ls == null) return;
|
||||
|
||||
foreach (var item in ls) {
|
||||
var key = _fsql.GetEntityKeyString(item);
|
||||
if (_states.ContainsKey(key)) {
|
||||
_fsql.MapEntityValue(item, _states[key].Value);
|
||||
_states[key].Time = DateTime.Now;
|
||||
} else {
|
||||
_states.Add(key, CreateEntityState(item));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ISelect<TEntity> Select => this.OrmSelect(null);
|
||||
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).Where(exp);
|
||||
@ -42,24 +70,6 @@ namespace FreeSql {
|
||||
ColumnInfo[] _tableIdentitys => _tableIdentitysPriv ?? (_tableIdentitysPriv = _table.Primarys.Where(a => a.Attribute.IsIdentity).ToArray());
|
||||
Type _entityType = typeof(TEntity);
|
||||
|
||||
bool _versionColumnPrivPrivIsInit = false;
|
||||
ColumnInfo _versionColumnPriv;
|
||||
ColumnInfo _versionColumn {
|
||||
get {
|
||||
if (_versionColumnPrivPrivIsInit == false) {
|
||||
var vc = _table.Properties.Where(a => _table.ColumnsByCs.ContainsKey(a.Key) && a.Value.GetCustomAttributes(typeof(VersionAttribute), false).Any());
|
||||
if (vc.Any()) {
|
||||
var col = _table.ColumnsByCs[vc.Last().Key];
|
||||
if (col.CsType.IsNullableType() || col.CsType.IsNumberType() == false)
|
||||
throw new Exception($"属性{col.CsName} 被标注为行级锁(Version),但其必须为数字类型,并且不可为 Nullable");
|
||||
_versionColumnPriv = col;
|
||||
}
|
||||
_versionColumnPrivPrivIsInit = true;
|
||||
}
|
||||
return _versionColumnPriv;
|
||||
}
|
||||
}
|
||||
|
||||
public class EntityState {
|
||||
public EntityState(TEntity value, string key) {
|
||||
this.Value = value;
|
||||
@ -202,35 +212,12 @@ namespace FreeSql {
|
||||
if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_fsql.GetEntityString(data)}");
|
||||
return false;
|
||||
}
|
||||
if (_states.TryGetValue(key, out var tryval) == false) {
|
||||
if (isThrow) throw new Exception($"不可更新,数据未被跟踪,应该先查询:{_fsql.GetEntityString(data)}");
|
||||
return false;
|
||||
}
|
||||
//if (_states.TryGetValue(key, out var tryval) == false) {
|
||||
// if (isThrow) throw new Exception($"不可删除,数据未被跟踪,应该先查询:{_fsql.GetEntityString(data)}");
|
||||
// return false;
|
||||
//}
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
|
||||
void TrackToList(object list) {
|
||||
if (list == null) return;
|
||||
var ls = list as IList<TEntity>;
|
||||
if (ls == null) return;
|
||||
|
||||
foreach (var item in ls) {
|
||||
var key = _fsql.GetEntityKeyString(item);
|
||||
if (_states.ContainsKey(key)) {
|
||||
_fsql.MapEntityValue(item, _states[key].Value);
|
||||
_states[key].Time = DateTime.Now;
|
||||
} else {
|
||||
_states.Add(key, CreateEntityState(item));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class BaseDbSet<TEntity> : DbSet<TEntity> where TEntity : class {
|
||||
|
||||
public BaseDbSet(DbContext ctx) {
|
||||
_ctx = ctx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +1,7 @@
|
||||
using FreeSql.Internal.Model;
|
||||
using FreeSql.Extensions.EntityUtil;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reflection;
|
||||
using FreeSql.Extensions;
|
||||
|
||||
namespace FreeSql {
|
||||
partial class DbSet<TEntity> {
|
||||
@ -22,25 +13,25 @@ namespace FreeSql {
|
||||
}
|
||||
|
||||
#region Add
|
||||
void AddPriv(TEntity source, bool isCheck) {
|
||||
if (isCheck && CanAdd(source, true) == false) return;
|
||||
void AddPriv(TEntity data, bool isCheck) {
|
||||
if (isCheck && CanAdd(data, true) == false) return;
|
||||
if (_tableIdentitys.Length > 0) {
|
||||
//有自增,马上执行
|
||||
switch (_fsql.Ado.DataType) {
|
||||
case DataType.SqlServer:
|
||||
case DataType.PostgreSQL:
|
||||
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) {
|
||||
_ctx.ExecCommand();
|
||||
var idtval = this.OrmInsert(source).ExecuteIdentity();
|
||||
_ctx._affrows++;
|
||||
_fsql.SetEntityIdentityValueWithPrimary(source, idtval);
|
||||
var state = CreateEntityState(source);
|
||||
ExecuteCommand();
|
||||
var idtval = this.OrmInsert(data).ExecuteIdentity();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(data, idtval);
|
||||
var state = CreateEntityState(data);
|
||||
_states.Add(state.Key, state);
|
||||
} else {
|
||||
_ctx.ExecCommand();
|
||||
var newval = this.OrmInsert(source).ExecuteInserted().First();
|
||||
_ctx._affrows++;
|
||||
_fsql.MapEntityValue(newval, source);
|
||||
ExecuteCommand();
|
||||
var newval = this.OrmInsert(data).ExecuteInserted().First();
|
||||
IncrAffrows(1);
|
||||
_fsql.MapEntityValue(newval, data);
|
||||
var state = CreateEntityState(newval);
|
||||
_states.Add(state.Key, state);
|
||||
}
|
||||
@ -49,21 +40,21 @@ namespace FreeSql {
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) {
|
||||
_ctx.ExecCommand();
|
||||
var idtval = this.OrmInsert(source).ExecuteIdentity();
|
||||
_ctx._affrows++;
|
||||
_fsql.SetEntityIdentityValueWithPrimary(source, idtval);
|
||||
var state = CreateEntityState(source);
|
||||
ExecuteCommand();
|
||||
var idtval = this.OrmInsert(data).ExecuteIdentity();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(data, idtval);
|
||||
var state = CreateEntityState(data);
|
||||
_states.Add(state.Key, state);
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
//进入队列,等待 SaveChanges 时执行
|
||||
_ctx.EnqueueAction(DbContext.ExecCommandInfoType.Insert, this, typeof(EntityState), CreateEntityState(source));
|
||||
EnqueueAction(DbContext.ExecCommandInfoType.Insert, this, typeof(EntityState), CreateEntityState(data));
|
||||
}
|
||||
}
|
||||
public void Add(TEntity source) => AddPriv(source, true);
|
||||
public void Add(TEntity data) => AddPriv(data, true);
|
||||
#endregion
|
||||
|
||||
#region AddRange
|
||||
@ -78,13 +69,13 @@ namespace FreeSql {
|
||||
switch (_fsql.Ado.DataType) {
|
||||
case DataType.SqlServer:
|
||||
case DataType.PostgreSQL:
|
||||
_ctx.ExecCommand();
|
||||
ExecuteCommand();
|
||||
var rets = this.OrmInsert(data).ExecuteInserted();
|
||||
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
|
||||
var idx = 0;
|
||||
foreach (var s in data)
|
||||
_fsql.MapEntityValue(rets[idx++], s);
|
||||
_ctx._affrows += rets.Count;
|
||||
IncrAffrows(rets.Count);
|
||||
TrackToList(rets);
|
||||
return;
|
||||
case DataType.MySql:
|
||||
@ -97,7 +88,7 @@ namespace FreeSql {
|
||||
} else {
|
||||
//进入队列,等待 SaveChanges 时执行
|
||||
foreach (var s in data)
|
||||
_ctx.EnqueueAction(DbContext.ExecCommandInfoType.Insert, this, typeof(EntityState), CreateEntityState(s));
|
||||
EnqueueAction(DbContext.ExecCommandInfoType.Insert, this, typeof(EntityState), CreateEntityState(s));
|
||||
}
|
||||
}
|
||||
public void AddRange(IEnumerable<TEntity> data) {
|
||||
@ -111,13 +102,13 @@ namespace FreeSql {
|
||||
switch (_fsql.Ado.DataType) {
|
||||
case DataType.SqlServer:
|
||||
case DataType.PostgreSQL:
|
||||
_ctx.ExecCommand();
|
||||
ExecuteCommand();
|
||||
var rets = this.OrmInsert(data).ExecuteInserted();
|
||||
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
|
||||
var idx = 0;
|
||||
foreach(var s in data)
|
||||
_fsql.MapEntityValue(rets[idx++], s);
|
||||
_ctx._affrows += rets.Count;
|
||||
IncrAffrows(rets.Count);
|
||||
TrackToList(rets);
|
||||
return;
|
||||
case DataType.MySql:
|
||||
@ -130,7 +121,7 @@ namespace FreeSql {
|
||||
} else {
|
||||
//进入队列,等待 SaveChanges 时执行
|
||||
foreach (var s in data)
|
||||
_ctx.EnqueueAction(DbContext.ExecCommandInfoType.Insert, this, typeof(EntityState), CreateEntityState(s));
|
||||
EnqueueAction(DbContext.ExecCommandInfoType.Insert, this, typeof(EntityState), CreateEntityState(s));
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
@ -168,42 +159,11 @@ namespace FreeSql {
|
||||
return data.Count;
|
||||
|
||||
var updateSource = data.Select(a => a.Value).ToArray();
|
||||
var update = this.OrmUpdate(null).SetSource(updateSource);
|
||||
|
||||
var isWhereVersion = false;
|
||||
if (_versionColumn != null) {
|
||||
if (cuig.Contains(_versionColumn.CsName)) {
|
||||
var parm1Exp = Expression.Parameter(_entityType, "a");
|
||||
var lambdExp = Expression.Lambda(
|
||||
typeof(Func<,>).MakeGenericType(_entityType, _versionColumn.CsType),
|
||||
Expression.Add(
|
||||
Expression.MakeMemberAccess(parm1Exp, _table.Properties[_versionColumn.CsName]),
|
||||
Expression.Convert(Expression.Constant(1), _versionColumn.CsType)
|
||||
),
|
||||
parm1Exp
|
||||
);
|
||||
update.AppendEntityUpdateSetWithColumn(_versionColumn.CsType, lambdExp);
|
||||
isWhereVersion = true;
|
||||
}
|
||||
}
|
||||
update.IgnoreColumns(cuig);
|
||||
|
||||
if (isWhereVersion)
|
||||
update.WhereCaseSource(_versionColumn.CsName, sqlval => sqlval);
|
||||
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
|
||||
|
||||
var affrows = update.ExecuteAffrows();
|
||||
|
||||
if (affrows != updateSource.Length) {
|
||||
if (_versionColumn != null)
|
||||
throw new Exception("数据未更新,其中的记录可能不存在,或者【行级乐观锁】版本过旧");
|
||||
throw new Exception("数据未更新,其中的记录可能不存在");
|
||||
}
|
||||
|
||||
foreach (var newval in data) {
|
||||
|
||||
if (isWhereVersion)
|
||||
_fsql.SetEntityIncrByWithPropertyName(newval.Value, _versionColumn.CsName, 1);
|
||||
|
||||
if (_states.TryGetValue(newval.Key, out var tryold))
|
||||
_fsql.MapEntityValue(newval.Value, tryold.Value);
|
||||
}
|
||||
@ -216,7 +176,7 @@ namespace FreeSql {
|
||||
|
||||
void UpdatePriv(TEntity data, bool isCheck) {
|
||||
if (isCheck && CanUpdate(data, true) == false) return;
|
||||
_ctx.EnqueueAction(DbContext.ExecCommandInfoType.Update, this, typeof(EntityState), CreateEntityState(data));
|
||||
EnqueueAction(DbContext.ExecCommandInfoType.Update, this, typeof(EntityState), CreateEntityState(data));
|
||||
}
|
||||
public void Update(TEntity data) => UpdatePriv(data, true);
|
||||
public void UpdateRange(TEntity[] data) {
|
||||
@ -233,14 +193,14 @@ namespace FreeSql {
|
||||
int DbContextBetchRemove(EntityState[] dels) {
|
||||
if (dels.Any() == false) return 0;
|
||||
var affrows = this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrows();
|
||||
return affrows;
|
||||
return Math.Max(dels.Length, affrows);
|
||||
}
|
||||
void RemovePriv(TEntity data, bool isCheck) {
|
||||
if (isCheck && CanRemove(data, true) == false) return;
|
||||
var state = CreateEntityState(data);
|
||||
_ctx.EnqueueAction(DbContext.ExecCommandInfoType.Delete, this, typeof(EntityState), state);
|
||||
EnqueueAction(DbContext.ExecCommandInfoType.Delete, this, typeof(EntityState), state);
|
||||
|
||||
_states.Remove(state.Key);
|
||||
if (_states.ContainsKey(state.Key)) _states.Remove(state.Key);
|
||||
_fsql.ClearEntityPrimaryValueWithIdentityAndGuid(data);
|
||||
}
|
||||
public void Remove(TEntity data) => RemovePriv(data, true);
|
||||
|
@ -1,7 +1,5 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace FreeSql {
|
||||
public static class DbContextDependencyInjection {
|
||||
|
@ -1,365 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
|
||||
namespace FreeSql.Extensions {
|
||||
public static class EntityUtilFreeSqlExtensions {
|
||||
|
||||
static MethodInfo MethodStringBuilderAppend = typeof(StringBuilder).GetMethod("Append", new Type[] { typeof(object) });
|
||||
static MethodInfo MethodStringBuilderToString = typeof(StringBuilder).GetMethod("ToString", new Type[0]);
|
||||
static PropertyInfo MethodStringBuilderLength = typeof(StringBuilder).GetProperty("Length");
|
||||
static MethodInfo MethodStringConcat = typeof(string).GetMethod("Concat", new Type[] { typeof(object) });
|
||||
|
||||
static ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Func<object, string>>> _dicGetEntityKeyString = new ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Func<object, string>>>();
|
||||
/// <summary>
|
||||
/// 获取实体的主键值,以 "*|_,[,_|*" 分割,当任意一个主键属性无值,返回 null
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="_table"></param>
|
||||
/// <param name="item"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetEntityKeyString<TEntity>(this IFreeSql orm, TEntity item, string splitString = "*|_,[,_|*") {
|
||||
var func = _dicGetEntityKeyString.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary<Type, Func<object, string>>()).GetOrAdd(typeof(TEntity), t => {
|
||||
var _table = orm.CodeFirst.GetTableByEntity(t);
|
||||
var pks = _table.Primarys;
|
||||
var returnTarget = Expression.Label(typeof(string));
|
||||
var parm1 = Expression.Parameter(typeof(object));
|
||||
var var1Parm = Expression.Variable(t);
|
||||
var var2Sb = Expression.Variable(typeof(StringBuilder));
|
||||
var var3IsNull = Expression.Variable(typeof(bool));
|
||||
var exps = new List<Expression>(new Expression[] {
|
||||
Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)),
|
||||
Expression.Assign(var2Sb, Expression.New(typeof(StringBuilder))),
|
||||
Expression.Assign(var3IsNull, Expression.Constant(false))
|
||||
});
|
||||
for (var a = 0; a < pks.Length; a++) {
|
||||
exps.Add(
|
||||
Expression.IfThen(
|
||||
Expression.IsFalse(var3IsNull),
|
||||
Expression.IfThenElse(
|
||||
Expression.Equal(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), Expression.Default(pks[a].CsType)),
|
||||
Expression.Assign(var3IsNull, Expression.Constant(true)),
|
||||
Expression.Block(
|
||||
new Expression[]{
|
||||
a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null,
|
||||
Expression.Call(var2Sb, MethodStringBuilderAppend,
|
||||
Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object))
|
||||
)
|
||||
}.Where(c => c != null).ToArray()
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
exps.Add(
|
||||
Expression.IfThen(
|
||||
Expression.IsFalse(var3IsNull),
|
||||
Expression.Return(returnTarget, Expression.Call(var2Sb, MethodStringBuilderToString))
|
||||
)
|
||||
);
|
||||
exps.Add(Expression.Label(returnTarget, Expression.Default(typeof(string))));
|
||||
return Expression.Lambda<Func<object, string>>(Expression.Block(new[] { var1Parm, var2Sb, var3IsNull }, exps), new[] { parm1 }).Compile();
|
||||
});
|
||||
return func(item);
|
||||
}
|
||||
static ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Func<object, string>>> _dicGetEntityString = new ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Func<object, string>>>();
|
||||
/// <summary>
|
||||
/// 获取实体的所有数据,以 (1, 2, xxx) 的形式
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="_table"></param>
|
||||
/// <param name="item"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetEntityString<TEntity>(this IFreeSql orm, TEntity item) {
|
||||
var func = _dicGetEntityString.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary<Type, Func<object, string>>()).GetOrAdd(typeof(TEntity), t => {
|
||||
var _table = orm.CodeFirst.GetTableByEntity(t);
|
||||
var cols = _table.Columns;
|
||||
var returnTarget = Expression.Label(typeof(string));
|
||||
var parm1 = Expression.Parameter(typeof(object));
|
||||
var var1Parm = Expression.Variable(t);
|
||||
var var2Sb = Expression.Variable(typeof(StringBuilder));
|
||||
var exps = new List<Expression>(new Expression[] {
|
||||
Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)),
|
||||
Expression.Assign(var2Sb, Expression.New(typeof(StringBuilder))),
|
||||
Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant("(" ))
|
||||
});
|
||||
var a = 0;
|
||||
foreach (var col in cols.Values) {
|
||||
exps.Add(
|
||||
Expression.Block(
|
||||
new Expression[]{
|
||||
a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(", " )) : null,
|
||||
Expression.Call(var2Sb, MethodStringBuilderAppend,
|
||||
Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[col.CsName]), typeof(object))
|
||||
)
|
||||
}.Where(c => c != null).ToArray()
|
||||
)
|
||||
);
|
||||
a++;
|
||||
}
|
||||
exps.AddRange(new Expression[] {
|
||||
Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(")" )),
|
||||
Expression.Return(returnTarget, Expression.Call(var2Sb, MethodStringBuilderToString)),
|
||||
Expression.Label(returnTarget, Expression.Default(typeof(string)))
|
||||
});
|
||||
return Expression.Lambda<Func<object, string>>(Expression.Block(new[] { var1Parm, var2Sb }, exps), new[] { parm1 }).Compile();
|
||||
});
|
||||
return func(item);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用新实体的值,复盖旧实体的值
|
||||
/// </summary>
|
||||
static ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Action<object, object>>> _dicCopyNewValueToEntity = new ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Action<object, object>>>();
|
||||
public static void MapEntityValue<TEntity>(this IFreeSql orm, TEntity from, TEntity to) {
|
||||
var func = _dicCopyNewValueToEntity.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary<Type, Action<object, object>>()).GetOrAdd(typeof(TEntity), t => {
|
||||
var _table = orm.CodeFirst.GetTableByEntity(t);
|
||||
var parm1 = Expression.Parameter(typeof(object));
|
||||
var parm2 = Expression.Parameter(typeof(object));
|
||||
var var1Parm = Expression.Variable(t);
|
||||
var var2Parm = Expression.Variable(t);
|
||||
var exps = new List<Expression>(new Expression[] {
|
||||
Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)),
|
||||
Expression.Assign(var2Parm, Expression.TypeAs(parm2, t))
|
||||
});
|
||||
foreach (var prop in _table.Properties.Values) {
|
||||
if (_table.ColumnsByCs.ContainsKey(prop.Name)) {
|
||||
exps.Add(
|
||||
Expression.Assign(
|
||||
Expression.MakeMemberAccess(var2Parm, prop),
|
||||
Expression.MakeMemberAccess(var1Parm, prop)
|
||||
)
|
||||
);
|
||||
} else {
|
||||
exps.Add(
|
||||
Expression.Assign(
|
||||
Expression.MakeMemberAccess(var2Parm, prop),
|
||||
Expression.Default(prop.PropertyType)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
return Expression.Lambda<Action<object, object>>(Expression.Block(new[] { var1Parm, var2Parm }, exps), new[] { parm1, parm2 }).Compile();
|
||||
});
|
||||
func(from, to);
|
||||
}
|
||||
|
||||
static ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Action<object, long>>> _dicSetEntityIdentityValueWithPrimary = new ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Action<object, long>>>();
|
||||
/// <summary>
|
||||
/// 设置实体中主键内的自增字段值(若存在)
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="orm"></param>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="idtval"></param>
|
||||
public static void SetEntityIdentityValueWithPrimary<TEntity>(this IFreeSql orm, TEntity item, long idtval) {
|
||||
var func = _dicSetEntityIdentityValueWithPrimary.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary<Type, Action<object, long>>()).GetOrAdd(typeof(TEntity), t => {
|
||||
var _table = orm.CodeFirst.GetTableByEntity(t);
|
||||
var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity);
|
||||
var parm1 = Expression.Parameter(typeof(object));
|
||||
var parm2 = Expression.Parameter(typeof(long));
|
||||
var var1Parm = Expression.Variable(t);
|
||||
var exps = new List<Expression>(new Expression[] {
|
||||
Expression.Assign(var1Parm, Expression.TypeAs(parm1, t))
|
||||
});
|
||||
if (identitys.Any()) {
|
||||
var idts0 = identitys.First();
|
||||
exps.Add(
|
||||
Expression.Assign(
|
||||
Expression.MakeMemberAccess(var1Parm, _table.Properties[idts0.CsName]),
|
||||
Expression.Convert(FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(idts0.CsType, Expression.Convert(parm2, typeof(object))), idts0.CsType)
|
||||
)
|
||||
);
|
||||
}
|
||||
return Expression.Lambda<Action<object, long>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2 }).Compile();
|
||||
});
|
||||
func(item, idtval);
|
||||
}
|
||||
static ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Func<object, long>>> _dicGetEntityIdentityValueWithPrimary = new ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Func<object, long>>>();
|
||||
/// <summary>
|
||||
/// 获取实体中主键内的自增字段值(若存在)
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="orm"></param>
|
||||
/// <param name="item"></param>
|
||||
public static long GetEntityIdentityValueWithPrimary<TEntity>(this IFreeSql orm, TEntity item) {
|
||||
var func = _dicGetEntityIdentityValueWithPrimary.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary<Type, Func<object, long>>()).GetOrAdd(typeof(TEntity), t => {
|
||||
var _table = orm.CodeFirst.GetTableByEntity(t);
|
||||
var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity);
|
||||
var returnTarget = Expression.Label(typeof(long));
|
||||
var parm1 = Expression.Parameter(typeof(object));
|
||||
var var1Parm = Expression.Variable(t);
|
||||
var exps = new List<Expression>(new Expression[] {
|
||||
Expression.Assign(var1Parm, Expression.TypeAs(parm1, t))
|
||||
});
|
||||
if (identitys.Any()) {
|
||||
var idts0 = identitys.First();
|
||||
exps.Add(
|
||||
Expression.IfThen(
|
||||
Expression.NotEqual(
|
||||
Expression.MakeMemberAccess(var1Parm, _table.Properties[idts0.CsName]),
|
||||
Expression.Default(idts0.CsType)
|
||||
),
|
||||
Expression.Return(
|
||||
returnTarget,
|
||||
FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(
|
||||
typeof(long),
|
||||
Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[idts0.CsName]), typeof(object))
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
exps.Add(Expression.Label(returnTarget, Expression.Default(typeof(long))));
|
||||
return Expression.Lambda<Func<object, long>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1 }).Compile();
|
||||
});
|
||||
return func(item);
|
||||
}
|
||||
|
||||
static ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Action<object>>> _dicClearEntityPrimaryValueWithIdentityAndGuid = new ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Action<object>>>();
|
||||
/// <summary>
|
||||
/// 清除实体的主键值,将自增、Guid类型的主键值清除
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="orm"></param>
|
||||
/// <param name="item"></param>
|
||||
public static void ClearEntityPrimaryValueWithIdentityAndGuid<TEntity>(this IFreeSql orm, TEntity item) {
|
||||
var func = _dicClearEntityPrimaryValueWithIdentityAndGuid.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary<Type, Action<object>>()).GetOrAdd(typeof(TEntity), t => {
|
||||
var _table = orm.CodeFirst.GetTableByEntity(t);
|
||||
var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity);
|
||||
var parm1 = Expression.Parameter(typeof(object));
|
||||
var var1Parm = Expression.Variable(t);
|
||||
var exps = new List<Expression>(new Expression[] {
|
||||
Expression.Assign(var1Parm, Expression.TypeAs(parm1, t))
|
||||
});
|
||||
foreach (var pk in _table.Primarys) {
|
||||
if (pk.CsType == typeof(Guid) || pk.CsType == typeof(Guid?) ||
|
||||
pk.Attribute.IsIdentity) {
|
||||
exps.Add(
|
||||
Expression.Assign(
|
||||
Expression.MakeMemberAccess(var1Parm, _table.Properties[pk.CsName]),
|
||||
Expression.Default(pk.CsType)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
return Expression.Lambda<Action<object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1 }).Compile();
|
||||
});
|
||||
func(item);
|
||||
}
|
||||
|
||||
static ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Func<object, object, bool, string[]>>> _dicCompareEntityValueReturnColumns = new ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Func<object, object, bool, string[]>>>();
|
||||
/// <summary>
|
||||
/// 对比两个实体值,返回相同/或不相同的列名
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="orm"></param>
|
||||
/// <param name="up"></param>
|
||||
/// <param name="oldval"></param>
|
||||
/// <returns></returns>
|
||||
public static string[] CompareEntityValueReturnColumns<TEntity>(this IFreeSql orm, TEntity up, TEntity oldval, bool isEqual) {
|
||||
var func = _dicCompareEntityValueReturnColumns.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary<Type, Func<object, object, bool, string[]>>()).GetOrAdd(typeof(TEntity), t => {
|
||||
var _table = orm.CodeFirst.GetTableByEntity(t);
|
||||
var returnTarget = Expression.Label(typeof(string[]));
|
||||
var parm1 = Expression.Parameter(typeof(object));
|
||||
var parm2 = Expression.Parameter(typeof(object));
|
||||
var parm3 = Expression.Parameter(typeof(bool));
|
||||
var var1Ret = Expression.Variable(typeof(List<string>));
|
||||
var var1Parm = Expression.Variable(t);
|
||||
var var2Parm = Expression.Variable(t);
|
||||
var exps = new List<Expression>(new Expression[] {
|
||||
Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)),
|
||||
Expression.Assign(var2Parm, Expression.TypeAs(parm2, t)),
|
||||
Expression.Assign(var1Ret, Expression.New(typeof(List<string>)))
|
||||
});
|
||||
var a = 0;
|
||||
foreach (var prop in _table.Properties.Values) {
|
||||
if (_table.ColumnsByCs.TryGetValue(prop.Name, out var trycol) == false) continue;
|
||||
exps.Add(
|
||||
Expression.IfThenElse(
|
||||
Expression.Equal(
|
||||
Expression.MakeMemberAccess(var1Parm, prop),
|
||||
Expression.MakeMemberAccess(var2Parm, prop)
|
||||
),
|
||||
Expression.IfThen(
|
||||
Expression.IsTrue(parm3),
|
||||
Expression.Call(var1Ret, typeof(List<string>).GetMethod("Add", new Type[] { typeof(string) }), Expression.Constant(trycol.Attribute.Name))
|
||||
),
|
||||
Expression.IfThen(
|
||||
Expression.IsFalse(parm3),
|
||||
Expression.Call(var1Ret, typeof(List<string>).GetMethod("Add", new Type[] { typeof(string) }), Expression.Constant(trycol.Attribute.Name))
|
||||
)
|
||||
)
|
||||
);
|
||||
a++;
|
||||
}
|
||||
exps.Add(Expression.Return(returnTarget, Expression.Call(var1Ret, typeof(List<string>).GetMethod("ToArray", new Type[0]))));
|
||||
exps.Add(Expression.Label(returnTarget, Expression.Constant(new string[0])));
|
||||
return Expression.Lambda<Func<object, object, bool, string[]>>(Expression.Block(new[] { var1Ret, var1Parm, var2Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
|
||||
});
|
||||
return func(up, oldval, isEqual);
|
||||
}
|
||||
|
||||
static ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Action<object, string, int>>> _dicSetEntityIncrByWithPropertyName = new ConcurrentDictionary<DataType, ConcurrentDictionary<Type, Action<object, string, int>>>();
|
||||
/// <summary>
|
||||
/// 设置实体中某属性的数值增加指定的值
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="orm"></param>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="idtval"></param>
|
||||
public static void SetEntityIncrByWithPropertyName<TEntity>(this IFreeSql orm, TEntity item, string propertyName, int incrBy) {
|
||||
var func = _dicSetEntityIncrByWithPropertyName.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary<Type, Action<object, string, int>>()).GetOrAdd(typeof(TEntity), t => {
|
||||
var _table = orm.CodeFirst.GetTableByEntity(t);
|
||||
var parm1 = Expression.Parameter(typeof(object));
|
||||
var parm2 = Expression.Parameter(typeof(string));
|
||||
var parm3 = Expression.Parameter(typeof(int));
|
||||
var var1Parm = Expression.Variable(t);
|
||||
var exps = new List<Expression>(new Expression[] {
|
||||
Expression.Assign(var1Parm, Expression.TypeAs(parm1, t))
|
||||
});
|
||||
if (_table.Properties.ContainsKey(propertyName)) {
|
||||
var prop = _table.Properties[propertyName];
|
||||
exps.Add(
|
||||
Expression.Assign(
|
||||
Expression.MakeMemberAccess(var1Parm, prop),
|
||||
Expression.Add(
|
||||
Expression.MakeMemberAccess(var1Parm, prop),
|
||||
Expression.Convert(
|
||||
FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(prop.PropertyType, Expression.Convert(parm3, typeof(object))),
|
||||
prop.PropertyType
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
return Expression.Lambda<Action<object, string, int>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
|
||||
});
|
||||
func(item, propertyName, incrBy);
|
||||
}
|
||||
|
||||
static ConcurrentDictionary<Type, MethodInfo[]> _dicAppendEntityUpdateSetWithColumnMethods = new ConcurrentDictionary<Type, MethodInfo[]>();
|
||||
static ConcurrentDictionary<Type, ConcurrentDictionary<Type, MethodInfo>> _dicAppendEntityUpdateSetWithColumnMethod = new ConcurrentDictionary<Type, ConcurrentDictionary<Type, MethodInfo>>();
|
||||
/// <summary>
|
||||
/// 缓存执行 IUpdate.Set
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="update"></param>
|
||||
/// <param name="columnType"></param>
|
||||
/// <param name="setExp"></param>
|
||||
public static void AppendEntityUpdateSetWithColumn<TEntity>(this IUpdate<TEntity> update, Type columnType, LambdaExpression setExp) where TEntity : class {
|
||||
|
||||
var setMethod = _dicAppendEntityUpdateSetWithColumnMethod.GetOrAdd(typeof(IUpdate<TEntity>), uptp => new ConcurrentDictionary<Type, MethodInfo>()).GetOrAdd(columnType, coltp => {
|
||||
var allMethods = _dicAppendEntityUpdateSetWithColumnMethods.GetOrAdd(typeof(IUpdate<TEntity>), uptp => uptp.GetMethods());
|
||||
return allMethods.Where(a => a.Name == "Set" && a.IsGenericMethod && a.GetParameters().Length == 1 && a.GetGenericArguments().First().Name == "TMember").FirstOrDefault()
|
||||
.MakeGenericMethod(columnType);
|
||||
});
|
||||
|
||||
setMethod.Invoke(update, new object[] { setExp });
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user