mirror of
https://github.com/nsnail/FreeSql.git
synced 2025-06-18 20:08:15 +08:00
源代码改用vs默认格式化
This commit is contained in:
@ -5,150 +5,168 @@ using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql {
|
||||
public abstract partial class DbContext : IDisposable {
|
||||
namespace FreeSql
|
||||
{
|
||||
public abstract partial class DbContext : IDisposable
|
||||
{
|
||||
|
||||
internal IFreeSql _orm;
|
||||
internal IFreeSql _fsql => _orm ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
|
||||
internal IFreeSql _orm;
|
||||
internal IFreeSql _fsql => _orm ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
|
||||
|
||||
public IFreeSql Orm => _fsql;
|
||||
public IFreeSql Orm => _fsql;
|
||||
|
||||
protected IUnitOfWork _uowPriv;
|
||||
internal IUnitOfWork _uow => _isUseUnitOfWork ? (_uowPriv ?? (_uowPriv = new UnitOfWork(_fsql))) : null;
|
||||
internal bool _isUseUnitOfWork = true; //不使用工作单元事务
|
||||
protected IUnitOfWork _uowPriv;
|
||||
internal IUnitOfWork _uow => _isUseUnitOfWork ? (_uowPriv ?? (_uowPriv = new UnitOfWork(_fsql))) : null;
|
||||
internal bool _isUseUnitOfWork = true; //不使用工作单元事务
|
||||
|
||||
public IUnitOfWork UnitOfWork => _uow;
|
||||
public IUnitOfWork UnitOfWork => _uow;
|
||||
|
||||
DbContextOptions _options;
|
||||
internal DbContextOptions Options {
|
||||
get {
|
||||
if (_options != null) return _options;
|
||||
if (FreeSqlDbContextExtenssions._dicSetDbContextOptions.TryGetValue(Orm, out _options)) return _options;
|
||||
_options = new DbContextOptions();
|
||||
return _options;
|
||||
}
|
||||
}
|
||||
DbContextOptions _options;
|
||||
internal DbContextOptions Options
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_options != null) return _options;
|
||||
if (FreeSqlDbContextExtenssions._dicSetDbContextOptions.TryGetValue(Orm, out _options)) return _options;
|
||||
_options = new DbContextOptions();
|
||||
return _options;
|
||||
}
|
||||
}
|
||||
|
||||
static ConcurrentDictionary<Type, PropertyInfo[]> _dicGetDbSetProps = new ConcurrentDictionary<Type, PropertyInfo[]>();
|
||||
protected DbContext() {
|
||||
static ConcurrentDictionary<Type, PropertyInfo[]> _dicGetDbSetProps = new ConcurrentDictionary<Type, PropertyInfo[]>();
|
||||
protected DbContext()
|
||||
{
|
||||
|
||||
var builder = new DbContextOptionsBuilder();
|
||||
OnConfiguring(builder);
|
||||
_orm = builder._fsql;
|
||||
var builder = new DbContextOptionsBuilder();
|
||||
OnConfiguring(builder);
|
||||
_orm = builder._fsql;
|
||||
|
||||
if (_orm != null) InitPropSets();
|
||||
}
|
||||
if (_orm != null) InitPropSets();
|
||||
}
|
||||
|
||||
internal void InitPropSets() {
|
||||
var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp =>
|
||||
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
|
||||
.Where(a => a.PropertyType.IsGenericType &&
|
||||
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());
|
||||
internal void InitPropSets()
|
||||
{
|
||||
var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp =>
|
||||
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
|
||||
.Where(a => a.PropertyType.IsGenericType &&
|
||||
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());
|
||||
|
||||
foreach (var prop in props) {
|
||||
var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);
|
||||
foreach (var prop in props)
|
||||
{
|
||||
var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);
|
||||
|
||||
prop.SetValue(this, set);
|
||||
AllSets.Add(prop.Name, set);
|
||||
}
|
||||
}
|
||||
prop.SetValue(this, set);
|
||||
AllSets.Add(prop.Name, set);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void OnConfiguring(DbContextOptionsBuilder builder) {
|
||||
|
||||
}
|
||||
protected virtual void OnConfiguring(DbContextOptionsBuilder builder)
|
||||
{
|
||||
|
||||
protected Dictionary<Type, IDbSet> _dicSet = new Dictionary<Type, IDbSet>();
|
||||
public DbSet<TEntity> Set<TEntity>() where TEntity : class => this.Set(typeof(TEntity)) as DbSet<TEntity>;
|
||||
public virtual IDbSet Set(Type entityType) {
|
||||
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
|
||||
var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(entityType), this) as IDbSet;
|
||||
if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
|
||||
return sd;
|
||||
}
|
||||
protected Dictionary<string, IDbSet> AllSets { get; } = new Dictionary<string, IDbSet>();
|
||||
}
|
||||
|
||||
#region DbSet 快速代理
|
||||
/// <summary>
|
||||
/// 添加
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void Add<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Add(data);
|
||||
public void AddRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRange(data);
|
||||
public Task AddAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddAsync(data);
|
||||
public Task AddRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRangeAsync(data);
|
||||
protected Dictionary<Type, IDbSet> _dicSet = new Dictionary<Type, IDbSet>();
|
||||
public DbSet<TEntity> Set<TEntity>() where TEntity : class => this.Set(typeof(TEntity)) as DbSet<TEntity>;
|
||||
public virtual IDbSet Set(Type entityType)
|
||||
{
|
||||
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
|
||||
var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(entityType), this) as IDbSet;
|
||||
if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
|
||||
return sd;
|
||||
}
|
||||
protected Dictionary<string, IDbSet> AllSets { get; } = new Dictionary<string, IDbSet>();
|
||||
|
||||
/// <summary>
|
||||
/// 更新
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void Update<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Update(data);
|
||||
public void UpdateRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRange(data);
|
||||
public Task UpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().UpdateAsync(data);
|
||||
public Task UpdateRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRangeAsync(data);
|
||||
#region DbSet 快速代理
|
||||
/// <summary>
|
||||
/// 添加
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void Add<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Add(data);
|
||||
public void AddRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRange(data);
|
||||
public Task AddAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddAsync(data);
|
||||
public Task AddRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRangeAsync(data);
|
||||
|
||||
/// <summary>
|
||||
/// 删除
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void Remove<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Remove(data);
|
||||
public void RemoveRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().RemoveRange(data);
|
||||
/// <summary>
|
||||
/// 更新
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void Update<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Update(data);
|
||||
public void UpdateRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRange(data);
|
||||
public Task UpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().UpdateAsync(data);
|
||||
public Task UpdateRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRangeAsync(data);
|
||||
|
||||
/// <summary>
|
||||
/// 添加或更新
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void AddOrUpdate<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdate(data);
|
||||
public Task AddOrUpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdateAsync(data);
|
||||
/// <summary>
|
||||
/// 删除
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void Remove<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Remove(data);
|
||||
public void RemoveRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().RemoveRange(data);
|
||||
|
||||
/// <summary>
|
||||
/// 附加实体,可用于不查询就更新或删除
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void Attach<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Attach(data);
|
||||
public void AttachRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AttachRange(data);
|
||||
#endregion
|
||||
/// <summary>
|
||||
/// 添加或更新
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void AddOrUpdate<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdate(data);
|
||||
public Task AddOrUpdateAsync<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().AddOrUpdateAsync(data);
|
||||
|
||||
internal class ExecCommandInfo {
|
||||
public ExecCommandInfoType actionType { get; set; }
|
||||
public IDbSet dbSet { get; set; }
|
||||
public Type stateType { get; set; }
|
||||
public object state { get; set; }
|
||||
}
|
||||
internal enum ExecCommandInfoType { Insert, Update, Delete }
|
||||
Queue<ExecCommandInfo> _actions = new Queue<ExecCommandInfo>();
|
||||
internal int _affrows = 0;
|
||||
/// <summary>
|
||||
/// 附加实体,可用于不查询就更新或删除
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
public void Attach<TEntity>(TEntity data) where TEntity : class => this.Set<TEntity>().Attach(data);
|
||||
public void AttachRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AttachRange(data);
|
||||
#endregion
|
||||
|
||||
internal void EnqueueAction(ExecCommandInfoType actionType, IDbSet dbSet, Type stateType, object state) {
|
||||
_actions.Enqueue(new ExecCommandInfo { actionType = actionType, dbSet = dbSet, stateType = stateType, state = state });
|
||||
}
|
||||
internal class ExecCommandInfo
|
||||
{
|
||||
public ExecCommandInfoType actionType { get; set; }
|
||||
public IDbSet dbSet { get; set; }
|
||||
public Type stateType { get; set; }
|
||||
public object state { get; set; }
|
||||
}
|
||||
internal enum ExecCommandInfoType { Insert, Update, Delete }
|
||||
Queue<ExecCommandInfo> _actions = new Queue<ExecCommandInfo>();
|
||||
internal int _affrows = 0;
|
||||
|
||||
~DbContext() {
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose() {
|
||||
if (_isdisposed) return;
|
||||
try {
|
||||
_actions.Clear();
|
||||
internal void EnqueueAction(ExecCommandInfoType actionType, IDbSet dbSet, Type stateType, object state)
|
||||
{
|
||||
_actions.Enqueue(new ExecCommandInfo { actionType = actionType, dbSet = dbSet, stateType = stateType, state = state });
|
||||
}
|
||||
|
||||
foreach (var set in _dicSet)
|
||||
try {
|
||||
set.Value.Dispose();
|
||||
} catch { }
|
||||
~DbContext()
|
||||
{
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose()
|
||||
{
|
||||
if (_isdisposed) return;
|
||||
try
|
||||
{
|
||||
_actions.Clear();
|
||||
|
||||
_dicSet.Clear();
|
||||
AllSets.Clear();
|
||||
|
||||
_uow?.Rollback();
|
||||
} finally {
|
||||
_isdisposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var set in _dicSet)
|
||||
try
|
||||
{
|
||||
set.Value.Dispose();
|
||||
}
|
||||
catch { }
|
||||
|
||||
_dicSet.Clear();
|
||||
AllSets.Clear();
|
||||
|
||||
_uow?.Rollback();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isdisposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,115 +5,133 @@ using System.Reflection;
|
||||
using System.Linq.Expressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql {
|
||||
partial class DbContext {
|
||||
namespace FreeSql
|
||||
{
|
||||
partial class DbContext
|
||||
{
|
||||
|
||||
async public virtual Task<int> SaveChangesAsync() {
|
||||
await ExecCommandAsync();
|
||||
_uow?.Commit();
|
||||
var ret = _affrows;
|
||||
_affrows = 0;
|
||||
return ret;
|
||||
}
|
||||
async public virtual Task<int> SaveChangesAsync()
|
||||
{
|
||||
await ExecCommandAsync();
|
||||
_uow?.Commit();
|
||||
var ret = _affrows;
|
||||
_affrows = 0;
|
||||
return ret;
|
||||
}
|
||||
|
||||
static Dictionary<Type, Dictionary<string, Func<object, object[], Task<int>>>> _dicExecCommandDbContextBetchAsync = new Dictionary<Type, Dictionary<string, Func<object, object[], Task<int>>>>();
|
||||
async internal Task ExecCommandAsync() {
|
||||
if (isExecCommanding) return;
|
||||
if (_actions.Any() == false) return;
|
||||
isExecCommanding = true;
|
||||
static Dictionary<Type, Dictionary<string, Func<object, object[], Task<int>>>> _dicExecCommandDbContextBetchAsync = new Dictionary<Type, Dictionary<string, Func<object, object[], Task<int>>>>();
|
||||
async internal Task ExecCommandAsync()
|
||||
{
|
||||
if (isExecCommanding) return;
|
||||
if (_actions.Any() == false) return;
|
||||
isExecCommanding = true;
|
||||
|
||||
ExecCommandInfo oldinfo = null;
|
||||
var states = new List<object>();
|
||||
ExecCommandInfo oldinfo = null;
|
||||
var states = new List<object>();
|
||||
|
||||
Func<string, Task<int>> dbContextBetch = methodName => {
|
||||
if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
|
||||
trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
|
||||
if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
|
||||
var arrType = oldinfo.stateType.MakeArrayType();
|
||||
var dbsetType = oldinfo.dbSet.GetType().BaseType;
|
||||
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
|
||||
Func<string, Task<int>> dbContextBetch = methodName =>
|
||||
{
|
||||
if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
|
||||
trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
|
||||
if (trydic.TryGetValue(methodName, out var tryfunc) == false)
|
||||
{
|
||||
var arrType = oldinfo.stateType.MakeArrayType();
|
||||
var dbsetType = oldinfo.dbSet.GetType().BaseType;
|
||||
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
|
||||
|
||||
var returnTarget = Expression.Label(typeof(Task<int>));
|
||||
var parm1DbSet = Expression.Parameter(typeof(object));
|
||||
var parm2Vals = Expression.Parameter(typeof(object[]));
|
||||
var var1Vals = Expression.Variable(arrType);
|
||||
tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
|
||||
new[] { var1Vals },
|
||||
Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
|
||||
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
|
||||
Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
|
||||
), new[] { parm1DbSet, parm2Vals }).Compile();
|
||||
trydic.Add(methodName, tryfunc);
|
||||
}
|
||||
return tryfunc(oldinfo.dbSet, states.ToArray());
|
||||
};
|
||||
Func<Task> funcDelete = async () => {
|
||||
_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
|
||||
states.Clear();
|
||||
};
|
||||
Func<Task> funcInsert = async () => {
|
||||
_affrows += await dbContextBetch("DbContextBetchAddAsync");
|
||||
states.Clear();
|
||||
};
|
||||
Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
|
||||
var affrows = 0;
|
||||
if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
|
||||
else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
|
||||
if (affrows == -999) { //最后一个元素已被删除
|
||||
states.RemoveAt(states.Count - 1);
|
||||
return;
|
||||
}
|
||||
if (affrows == -998 || affrows == -997) { //没有执行更新
|
||||
var laststate = states[states.Count - 1];
|
||||
states.Clear();
|
||||
if (affrows == -997) states.Add(laststate); //保留最后一个
|
||||
}
|
||||
if (affrows > 0) {
|
||||
_affrows += affrows;
|
||||
var islastNotUpdated = states.Count != affrows;
|
||||
var laststate = states[states.Count - 1];
|
||||
states.Clear();
|
||||
if (islastNotUpdated) states.Add(laststate); //保留最后一个
|
||||
}
|
||||
};
|
||||
var returnTarget = Expression.Label(typeof(Task<int>));
|
||||
var parm1DbSet = Expression.Parameter(typeof(object));
|
||||
var parm2Vals = Expression.Parameter(typeof(object[]));
|
||||
var var1Vals = Expression.Variable(arrType);
|
||||
tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
|
||||
new[] { var1Vals },
|
||||
Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
|
||||
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
|
||||
Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
|
||||
), new[] { parm1DbSet, parm2Vals }).Compile();
|
||||
trydic.Add(methodName, tryfunc);
|
||||
}
|
||||
return tryfunc(oldinfo.dbSet, states.ToArray());
|
||||
};
|
||||
Func<Task> funcDelete = async () =>
|
||||
{
|
||||
_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
|
||||
states.Clear();
|
||||
};
|
||||
Func<Task> funcInsert = async () =>
|
||||
{
|
||||
_affrows += await dbContextBetch("DbContextBetchAddAsync");
|
||||
states.Clear();
|
||||
};
|
||||
Func<bool, Task> funcUpdate = async (isLiveUpdate) =>
|
||||
{
|
||||
var affrows = 0;
|
||||
if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
|
||||
else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
|
||||
if (affrows == -999)
|
||||
{ //最后一个元素已被删除
|
||||
states.RemoveAt(states.Count - 1);
|
||||
return;
|
||||
}
|
||||
if (affrows == -998 || affrows == -997)
|
||||
{ //没有执行更新
|
||||
var laststate = states[states.Count - 1];
|
||||
states.Clear();
|
||||
if (affrows == -997) states.Add(laststate); //保留最后一个
|
||||
}
|
||||
if (affrows > 0)
|
||||
{
|
||||
_affrows += affrows;
|
||||
var islastNotUpdated = states.Count != affrows;
|
||||
var laststate = states[states.Count - 1];
|
||||
states.Clear();
|
||||
if (islastNotUpdated) states.Add(laststate); //保留最后一个
|
||||
}
|
||||
};
|
||||
|
||||
while (_actions.Any() || states.Any()) {
|
||||
var info = _actions.Any() ? _actions.Dequeue() : null;
|
||||
if (oldinfo == null) oldinfo = info;
|
||||
var isLiveUpdate = false;
|
||||
while (_actions.Any() || states.Any())
|
||||
{
|
||||
var info = _actions.Any() ? _actions.Dequeue() : null;
|
||||
if (oldinfo == null) oldinfo = info;
|
||||
var isLiveUpdate = false;
|
||||
|
||||
if (_actions.Any() == false && states.Any() ||
|
||||
info != null && oldinfo.actionType != info.actionType ||
|
||||
info != null && oldinfo.stateType != info.stateType) {
|
||||
if (_actions.Any() == false && states.Any() ||
|
||||
info != null && oldinfo.actionType != info.actionType ||
|
||||
info != null && oldinfo.stateType != info.stateType)
|
||||
{
|
||||
|
||||
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
|
||||
//最后一个,合起来发送
|
||||
states.Add(info.state);
|
||||
info = null;
|
||||
}
|
||||
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType)
|
||||
{
|
||||
//最后一个,合起来发送
|
||||
states.Add(info.state);
|
||||
info = null;
|
||||
}
|
||||
|
||||
switch (oldinfo.actionType) {
|
||||
case ExecCommandInfoType.Insert:
|
||||
await funcInsert();
|
||||
break;
|
||||
case ExecCommandInfoType.Delete:
|
||||
await funcDelete();
|
||||
break;
|
||||
}
|
||||
isLiveUpdate = true;
|
||||
}
|
||||
switch (oldinfo.actionType)
|
||||
{
|
||||
case ExecCommandInfoType.Insert:
|
||||
await funcInsert();
|
||||
break;
|
||||
case ExecCommandInfoType.Delete:
|
||||
await funcDelete();
|
||||
break;
|
||||
}
|
||||
isLiveUpdate = true;
|
||||
}
|
||||
|
||||
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
|
||||
if (states.Any())
|
||||
await funcUpdate(isLiveUpdate);
|
||||
}
|
||||
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update)
|
||||
{
|
||||
if (states.Any())
|
||||
await funcUpdate(isLiveUpdate);
|
||||
}
|
||||
|
||||
if (info != null) {
|
||||
states.Add(info.state);
|
||||
oldinfo = info;
|
||||
}
|
||||
}
|
||||
isExecCommanding = false;
|
||||
}
|
||||
}
|
||||
if (info != null)
|
||||
{
|
||||
states.Add(info.state);
|
||||
oldinfo = info;
|
||||
}
|
||||
}
|
||||
isExecCommanding = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,12 @@
|
||||
|
||||
namespace FreeSql {
|
||||
public class DbContextOptions {
|
||||
namespace FreeSql
|
||||
{
|
||||
public class DbContextOptions
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 是否开启一对多,联级保存功能
|
||||
/// </summary>
|
||||
public bool EnableAddOrUpdateNavigateList { get; set; } = true;
|
||||
}
|
||||
/// <summary>
|
||||
/// 是否开启一对多,联级保存功能
|
||||
/// </summary>
|
||||
public bool EnableAddOrUpdateNavigateList { get; set; } = true;
|
||||
}
|
||||
}
|
||||
|
@ -1,13 +1,16 @@
|
||||
|
||||
|
||||
namespace FreeSql {
|
||||
public class DbContextOptionsBuilder {
|
||||
namespace FreeSql
|
||||
{
|
||||
public class DbContextOptionsBuilder
|
||||
{
|
||||
|
||||
internal IFreeSql _fsql;
|
||||
internal IFreeSql _fsql;
|
||||
|
||||
public DbContextOptionsBuilder UseFreeSql(IFreeSql orm) {
|
||||
_fsql = orm;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
public DbContextOptionsBuilder UseFreeSql(IFreeSql orm)
|
||||
{
|
||||
_fsql = orm;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -4,116 +4,134 @@ using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace FreeSql {
|
||||
partial class DbContext {
|
||||
namespace FreeSql
|
||||
{
|
||||
partial class DbContext
|
||||
{
|
||||
|
||||
public virtual int SaveChanges() {
|
||||
ExecCommand();
|
||||
_uow?.Commit();
|
||||
var ret = _affrows;
|
||||
_affrows = 0;
|
||||
return ret;
|
||||
}
|
||||
public virtual int SaveChanges()
|
||||
{
|
||||
ExecCommand();
|
||||
_uow?.Commit();
|
||||
var ret = _affrows;
|
||||
_affrows = 0;
|
||||
return ret;
|
||||
}
|
||||
|
||||
static Dictionary<Type, Dictionary<string, Func<object, object[], int>>> _dicExecCommandDbContextBetch = new Dictionary<Type, Dictionary<string, Func<object, object[], int>>>();
|
||||
bool isExecCommanding = false;
|
||||
internal void ExecCommand() {
|
||||
if (isExecCommanding) return;
|
||||
if (_actions.Any() == false) return;
|
||||
isExecCommanding = true;
|
||||
static Dictionary<Type, Dictionary<string, Func<object, object[], int>>> _dicExecCommandDbContextBetch = new Dictionary<Type, Dictionary<string, Func<object, object[], int>>>();
|
||||
bool isExecCommanding = false;
|
||||
internal void ExecCommand()
|
||||
{
|
||||
if (isExecCommanding) return;
|
||||
if (_actions.Any() == false) return;
|
||||
isExecCommanding = true;
|
||||
|
||||
ExecCommandInfo oldinfo = null;
|
||||
var states = new List<object>();
|
||||
ExecCommandInfo oldinfo = null;
|
||||
var states = new List<object>();
|
||||
|
||||
Func<string, int> dbContextBetch = methodName => {
|
||||
if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
|
||||
trydic = new Dictionary<string, Func<object, object[], int>>();
|
||||
if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
|
||||
var arrType = oldinfo.stateType.MakeArrayType();
|
||||
var dbsetType = oldinfo.dbSet.GetType().BaseType;
|
||||
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
|
||||
Func<string, int> dbContextBetch = methodName =>
|
||||
{
|
||||
if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
|
||||
trydic = new Dictionary<string, Func<object, object[], int>>();
|
||||
if (trydic.TryGetValue(methodName, out var tryfunc) == false)
|
||||
{
|
||||
var arrType = oldinfo.stateType.MakeArrayType();
|
||||
var dbsetType = oldinfo.dbSet.GetType().BaseType;
|
||||
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
|
||||
|
||||
var returnTarget = Expression.Label(typeof(int));
|
||||
var parm1DbSet = Expression.Parameter(typeof(object));
|
||||
var parm2Vals = Expression.Parameter(typeof(object[]));
|
||||
var var1Vals = Expression.Variable(arrType);
|
||||
tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
|
||||
new[] { var1Vals },
|
||||
Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
|
||||
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
|
||||
Expression.Label(returnTarget, Expression.Default(typeof(int)))
|
||||
), new[] { parm1DbSet, parm2Vals }).Compile();
|
||||
trydic.Add(methodName, tryfunc);
|
||||
}
|
||||
return tryfunc(oldinfo.dbSet, states.ToArray());
|
||||
};
|
||||
Action funcDelete = () => {
|
||||
_affrows += dbContextBetch("DbContextBetchRemove");
|
||||
states.Clear();
|
||||
};
|
||||
Action funcInsert = () => {
|
||||
_affrows += dbContextBetch("DbContextBetchAdd");
|
||||
states.Clear();
|
||||
};
|
||||
Action<bool> funcUpdate = isLiveUpdate => {
|
||||
var affrows = 0;
|
||||
if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
|
||||
else affrows = dbContextBetch("DbContextBetchUpdate");
|
||||
if (affrows == -999) { //最后一个元素已被删除
|
||||
states.RemoveAt(states.Count - 1);
|
||||
return;
|
||||
}
|
||||
if (affrows == -998 || affrows == -997) { //没有执行更新
|
||||
var laststate = states[states.Count - 1];
|
||||
states.Clear();
|
||||
if (affrows == -997) states.Add(laststate); //保留最后一个
|
||||
}
|
||||
if (affrows > 0) {
|
||||
_affrows += affrows;
|
||||
var islastNotUpdated = states.Count != affrows;
|
||||
var laststate = states[states.Count - 1];
|
||||
states.Clear();
|
||||
if (islastNotUpdated) states.Add(laststate); //保留最后一个
|
||||
}
|
||||
};
|
||||
var returnTarget = Expression.Label(typeof(int));
|
||||
var parm1DbSet = Expression.Parameter(typeof(object));
|
||||
var parm2Vals = Expression.Parameter(typeof(object[]));
|
||||
var var1Vals = Expression.Variable(arrType);
|
||||
tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
|
||||
new[] { var1Vals },
|
||||
Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
|
||||
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
|
||||
Expression.Label(returnTarget, Expression.Default(typeof(int)))
|
||||
), new[] { parm1DbSet, parm2Vals }).Compile();
|
||||
trydic.Add(methodName, tryfunc);
|
||||
}
|
||||
return tryfunc(oldinfo.dbSet, states.ToArray());
|
||||
};
|
||||
Action funcDelete = () =>
|
||||
{
|
||||
_affrows += dbContextBetch("DbContextBetchRemove");
|
||||
states.Clear();
|
||||
};
|
||||
Action funcInsert = () =>
|
||||
{
|
||||
_affrows += dbContextBetch("DbContextBetchAdd");
|
||||
states.Clear();
|
||||
};
|
||||
Action<bool> funcUpdate = isLiveUpdate =>
|
||||
{
|
||||
var affrows = 0;
|
||||
if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
|
||||
else affrows = dbContextBetch("DbContextBetchUpdate");
|
||||
if (affrows == -999)
|
||||
{ //最后一个元素已被删除
|
||||
states.RemoveAt(states.Count - 1);
|
||||
return;
|
||||
}
|
||||
if (affrows == -998 || affrows == -997)
|
||||
{ //没有执行更新
|
||||
var laststate = states[states.Count - 1];
|
||||
states.Clear();
|
||||
if (affrows == -997) states.Add(laststate); //保留最后一个
|
||||
}
|
||||
if (affrows > 0)
|
||||
{
|
||||
_affrows += affrows;
|
||||
var islastNotUpdated = states.Count != affrows;
|
||||
var laststate = states[states.Count - 1];
|
||||
states.Clear();
|
||||
if (islastNotUpdated) states.Add(laststate); //保留最后一个
|
||||
}
|
||||
};
|
||||
|
||||
while (_actions.Any() || states.Any()) {
|
||||
var info = _actions.Any() ? _actions.Dequeue() : null;
|
||||
if (oldinfo == null) oldinfo = info;
|
||||
var isLiveUpdate = false;
|
||||
while (_actions.Any() || states.Any())
|
||||
{
|
||||
var info = _actions.Any() ? _actions.Dequeue() : null;
|
||||
if (oldinfo == null) oldinfo = info;
|
||||
var isLiveUpdate = false;
|
||||
|
||||
if (_actions.Any() == false && states.Any() ||
|
||||
info != null && oldinfo.actionType != info.actionType ||
|
||||
info != null && oldinfo.stateType != info.stateType) {
|
||||
if (_actions.Any() == false && states.Any() ||
|
||||
info != null && oldinfo.actionType != info.actionType ||
|
||||
info != null && oldinfo.stateType != info.stateType)
|
||||
{
|
||||
|
||||
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
|
||||
//最后一个,合起来发送
|
||||
states.Add(info.state);
|
||||
info = null;
|
||||
}
|
||||
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType)
|
||||
{
|
||||
//最后一个,合起来发送
|
||||
states.Add(info.state);
|
||||
info = null;
|
||||
}
|
||||
|
||||
switch (oldinfo.actionType) {
|
||||
case ExecCommandInfoType.Insert:
|
||||
funcInsert();
|
||||
break;
|
||||
case ExecCommandInfoType.Delete:
|
||||
funcDelete();
|
||||
break;
|
||||
}
|
||||
isLiveUpdate = true;
|
||||
}
|
||||
switch (oldinfo.actionType)
|
||||
{
|
||||
case ExecCommandInfoType.Insert:
|
||||
funcInsert();
|
||||
break;
|
||||
case ExecCommandInfoType.Delete:
|
||||
funcDelete();
|
||||
break;
|
||||
}
|
||||
isLiveUpdate = true;
|
||||
}
|
||||
|
||||
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
|
||||
if (states.Any())
|
||||
funcUpdate(isLiveUpdate);
|
||||
}
|
||||
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update)
|
||||
{
|
||||
if (states.Any())
|
||||
funcUpdate(isLiveUpdate);
|
||||
}
|
||||
|
||||
if (info != null) {
|
||||
states.Add(info.state);
|
||||
oldinfo = info;
|
||||
}
|
||||
}
|
||||
isExecCommanding = false;
|
||||
}
|
||||
}
|
||||
if (info != null)
|
||||
{
|
||||
states.Add(info.state);
|
||||
oldinfo = info;
|
||||
}
|
||||
}
|
||||
isExecCommanding = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,13 @@
|
||||
|
||||
|
||||
namespace FreeSql {
|
||||
public class FreeContext : DbContext {
|
||||
namespace FreeSql
|
||||
{
|
||||
public class FreeContext : DbContext
|
||||
{
|
||||
|
||||
public FreeContext(IFreeSql orm) {
|
||||
_orm = orm;
|
||||
}
|
||||
}
|
||||
public FreeContext(IFreeSql orm)
|
||||
{
|
||||
_orm = orm;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -8,274 +8,326 @@ using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace FreeSql {
|
||||
namespace FreeSql
|
||||
{
|
||||
|
||||
internal class DbContextDbSet<TEntity> : DbSet<TEntity> where TEntity : class {
|
||||
internal class DbContextDbSet<TEntity> : DbSet<TEntity> where TEntity : class
|
||||
{
|
||||
|
||||
public DbContextDbSet(DbContext ctx) {
|
||||
_ctx = ctx;
|
||||
_uow = ctx._uow;
|
||||
_fsql = ctx._fsql;
|
||||
}
|
||||
}
|
||||
public DbContextDbSet(DbContext ctx)
|
||||
{
|
||||
_ctx = ctx;
|
||||
_uow = ctx._uow;
|
||||
_fsql = ctx._fsql;
|
||||
}
|
||||
}
|
||||
|
||||
public interface IDbSet : IDisposable {
|
||||
Type EntityType { get; }
|
||||
}
|
||||
public abstract partial class DbSet<TEntity> : IDbSet where TEntity : class {
|
||||
public interface IDbSet : IDisposable
|
||||
{
|
||||
Type EntityType { get; }
|
||||
}
|
||||
public abstract partial class DbSet<TEntity> : IDbSet where TEntity : class
|
||||
{
|
||||
|
||||
internal DbContext _ctx;
|
||||
internal IUnitOfWork _uow;
|
||||
internal IFreeSql _fsql;
|
||||
internal DbContext _ctx;
|
||||
internal IUnitOfWork _uow;
|
||||
internal IFreeSql _fsql;
|
||||
|
||||
protected virtual ISelect<TEntity> OrmSelect(object dywhere) {
|
||||
DbContextExecCommand(); //查询前先提交,否则会出脏读
|
||||
return _fsql.Select<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction(false)).TrackToList(TrackToList).WhereDynamic(dywhere);
|
||||
}
|
||||
protected virtual ISelect<TEntity> OrmSelect(object dywhere)
|
||||
{
|
||||
DbContextExecCommand(); //查询前先提交,否则会出脏读
|
||||
return _fsql.Select<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction(false)).TrackToList(TrackToList).WhereDynamic(dywhere);
|
||||
}
|
||||
|
||||
~DbSet() {
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose() {
|
||||
if (_isdisposed) return;
|
||||
try {
|
||||
this._dicUpdateTimes.Clear();
|
||||
this._states.Clear();
|
||||
} finally {
|
||||
_isdisposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
~DbSet()
|
||||
{
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose()
|
||||
{
|
||||
if (_isdisposed) return;
|
||||
try
|
||||
{
|
||||
this._dicUpdateTimes.Clear();
|
||||
this._states.Clear();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isdisposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual IInsert<TEntity> OrmInsert() => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction());
|
||||
protected virtual IInsert<TEntity> OrmInsert(TEntity data) => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data);
|
||||
protected virtual IInsert<TEntity> OrmInsert(IEnumerable<TEntity> data) => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data);
|
||||
protected virtual IInsert<TEntity> OrmInsert() => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction());
|
||||
protected virtual IInsert<TEntity> OrmInsert(TEntity data) => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data);
|
||||
protected virtual IInsert<TEntity> OrmInsert(IEnumerable<TEntity> data) => _fsql.Insert<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data);
|
||||
|
||||
protected virtual IUpdate<TEntity> OrmUpdate(IEnumerable<TEntity> entitys) => _fsql.Update<TEntity>().AsType(_entityType).SetSource(entitys).WithTransaction(_uow?.GetOrBeginTransaction());
|
||||
protected virtual IDelete<TEntity> OrmDelete(object dywhere) => _fsql.Delete<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).WhereDynamic(dywhere);
|
||||
protected virtual IUpdate<TEntity> OrmUpdate(IEnumerable<TEntity> entitys) => _fsql.Update<TEntity>().AsType(_entityType).SetSource(entitys).WithTransaction(_uow?.GetOrBeginTransaction());
|
||||
protected virtual IDelete<TEntity> OrmDelete(object dywhere) => _fsql.Delete<TEntity>().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).WhereDynamic(dywhere);
|
||||
|
||||
internal void EnqueueToDbContext(DbContext.ExecCommandInfoType actionType, EntityState state) {
|
||||
_ctx.EnqueueAction(actionType, this, typeof(EntityState), state);
|
||||
}
|
||||
internal void IncrAffrows(int affrows) {
|
||||
_ctx._affrows += affrows;
|
||||
}
|
||||
internal void EnqueueToDbContext(DbContext.ExecCommandInfoType actionType, EntityState state)
|
||||
{
|
||||
_ctx.EnqueueAction(actionType, this, typeof(EntityState), state);
|
||||
}
|
||||
internal void IncrAffrows(int affrows)
|
||||
{
|
||||
_ctx._affrows += affrows;
|
||||
}
|
||||
|
||||
internal void TrackToList(object list) {
|
||||
if (list == null) return;
|
||||
var ls = list as IList<TEntity>;
|
||||
if (ls == null) {
|
||||
var ie = list as IEnumerable;
|
||||
if (ie == null) return;
|
||||
foreach (var item in ie) {
|
||||
if (item == null) return;
|
||||
var itemType = item.GetType();
|
||||
if (itemType == typeof(object)) return;
|
||||
if (itemType.FullName.StartsWith("Submission#")) itemType = itemType.BaseType;
|
||||
var dbset = _ctx.Set(itemType);
|
||||
dbset?.GetType().GetMethod("TrackToList", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(dbset, new object[] { list });
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
internal void TrackToList(object list)
|
||||
{
|
||||
if (list == null) return;
|
||||
var ls = list as IList<TEntity>;
|
||||
if (ls == null)
|
||||
{
|
||||
var ie = list as IEnumerable;
|
||||
if (ie == null) return;
|
||||
foreach (var item in ie)
|
||||
{
|
||||
if (item == null) return;
|
||||
var itemType = item.GetType();
|
||||
if (itemType == typeof(object)) return;
|
||||
if (itemType.FullName.StartsWith("Submission#")) itemType = itemType.BaseType;
|
||||
var dbset = _ctx.Set(itemType);
|
||||
dbset?.GetType().GetMethod("TrackToList", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(dbset, new object[] { list });
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var item in ls) {
|
||||
var key = _fsql.GetEntityKeyString(_entityType, item, false);
|
||||
if (key == null) continue;
|
||||
_states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => {
|
||||
_fsql.MapEntityValue(_entityType, item, ov.Value);
|
||||
ov.Time = DateTime.Now;
|
||||
return ov;
|
||||
});
|
||||
}
|
||||
}
|
||||
foreach (var item in ls)
|
||||
{
|
||||
var key = _fsql.GetEntityKeyString(_entityType, item, false);
|
||||
if (key == null) continue;
|
||||
_states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) =>
|
||||
{
|
||||
_fsql.MapEntityValue(_entityType, item, ov.Value);
|
||||
ov.Time = DateTime.Now;
|
||||
return ov;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public ISelect<TEntity> Select => this.OrmSelect(null);
|
||||
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).Where(exp);
|
||||
public ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).WhereIf(condition, exp);
|
||||
public ISelect<TEntity> Select => this.OrmSelect(null);
|
||||
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).Where(exp);
|
||||
public ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => this.OrmSelect(null).WhereIf(condition, exp);
|
||||
|
||||
protected ConcurrentDictionary<string, EntityState> _states = new ConcurrentDictionary<string, EntityState>();
|
||||
internal ConcurrentDictionary<string, EntityState> _statesInternal => _states;
|
||||
TableInfo _tablePriv;
|
||||
protected TableInfo _table => _tablePriv ?? (_tablePriv = _fsql.CodeFirst.GetTableByEntity(_entityType));
|
||||
ColumnInfo[] _tableIdentitysPriv;
|
||||
protected ColumnInfo[] _tableIdentitys => _tableIdentitysPriv ?? (_tableIdentitysPriv = _table.Primarys.Where(a => a.Attribute.IsIdentity).ToArray());
|
||||
protected Type _entityType = typeof(TEntity);
|
||||
public Type EntityType => _entityType;
|
||||
protected ConcurrentDictionary<string, EntityState> _states = new ConcurrentDictionary<string, EntityState>();
|
||||
internal ConcurrentDictionary<string, EntityState> _statesInternal => _states;
|
||||
TableInfo _tablePriv;
|
||||
protected TableInfo _table => _tablePriv ?? (_tablePriv = _fsql.CodeFirst.GetTableByEntity(_entityType));
|
||||
ColumnInfo[] _tableIdentitysPriv;
|
||||
protected ColumnInfo[] _tableIdentitys => _tableIdentitysPriv ?? (_tableIdentitysPriv = _table.Primarys.Where(a => a.Attribute.IsIdentity).ToArray());
|
||||
protected Type _entityType = typeof(TEntity);
|
||||
public Type EntityType => _entityType;
|
||||
|
||||
/// <summary>
|
||||
/// 动态Type,在使用 DbSet<object> 后使用本方法,指定实体类型
|
||||
/// </summary>
|
||||
/// <param name="entityType"></param>
|
||||
/// <returns></returns>
|
||||
public void AsType(Type entityType) {
|
||||
if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object");
|
||||
if (entityType == _entityType) return;
|
||||
var newtb = _fsql.CodeFirst.GetTableByEntity(entityType);
|
||||
_entityType = entityType;
|
||||
_tablePriv = newtb ?? throw new Exception("DbSet.AsType 参数错误,请传入正确的实体类型");
|
||||
_tableIdentitysPriv = null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 动态Type,在使用 DbSet<object> 后使用本方法,指定实体类型
|
||||
/// </summary>
|
||||
/// <param name="entityType"></param>
|
||||
/// <returns></returns>
|
||||
public void AsType(Type entityType)
|
||||
{
|
||||
if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object");
|
||||
if (entityType == _entityType) return;
|
||||
var newtb = _fsql.CodeFirst.GetTableByEntity(entityType);
|
||||
_entityType = entityType;
|
||||
_tablePriv = newtb ?? throw new Exception("DbSet.AsType 参数错误,请传入正确的实体类型");
|
||||
_tableIdentitysPriv = null;
|
||||
}
|
||||
|
||||
public class EntityState {
|
||||
public EntityState(TEntity value, string key) {
|
||||
this.Value = value;
|
||||
this.Key = key;
|
||||
this.Time = DateTime.Now;
|
||||
}
|
||||
public TEntity OldValue { get; set; }
|
||||
public TEntity Value { get; set; }
|
||||
public string Key { get; set; }
|
||||
public DateTime Time { get; set; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 附加实体,可用于不查询就更新或删除
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void Attach(TEntity data) => AttachRange(new[] { data });
|
||||
public void AttachRange(IEnumerable<TEntity> data) {
|
||||
if (data == null || data.Any() == false) return;
|
||||
if (_table.Primarys.Any() == false) throw new Exception($"不可附加,实体没有主键:{_fsql.GetEntityString(_entityType, data.First())}");
|
||||
foreach (var item in data) {
|
||||
var key = _fsql.GetEntityKeyString(_entityType, item, false);
|
||||
if (string.IsNullOrEmpty(key)) throw new Exception($"不可附加,未设置主键的值:{_fsql.GetEntityString(_entityType, item)}");
|
||||
public class EntityState
|
||||
{
|
||||
public EntityState(TEntity value, string key)
|
||||
{
|
||||
this.Value = value;
|
||||
this.Key = key;
|
||||
this.Time = DateTime.Now;
|
||||
}
|
||||
public TEntity OldValue { get; set; }
|
||||
public TEntity Value { get; set; }
|
||||
public string Key { get; set; }
|
||||
public DateTime Time { get; set; }
|
||||
}
|
||||
/// <summary>
|
||||
/// 附加实体,可用于不查询就更新或删除
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void Attach(TEntity data) => AttachRange(new[] { data });
|
||||
public void AttachRange(IEnumerable<TEntity> data)
|
||||
{
|
||||
if (data == null || data.Any() == false) return;
|
||||
if (_table.Primarys.Any() == false) throw new Exception($"不可附加,实体没有主键:{_fsql.GetEntityString(_entityType, data.First())}");
|
||||
foreach (var item in data)
|
||||
{
|
||||
var key = _fsql.GetEntityKeyString(_entityType, item, false);
|
||||
if (string.IsNullOrEmpty(key)) throw new Exception($"不可附加,未设置主键的值:{_fsql.GetEntityString(_entityType, item)}");
|
||||
|
||||
_states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => {
|
||||
_fsql.MapEntityValue(_entityType, item, ov.Value);
|
||||
ov.Time = DateTime.Now;
|
||||
return ov;
|
||||
});
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 清空状态数据
|
||||
/// </summary>
|
||||
public void FlushState() {
|
||||
_states.Clear();
|
||||
}
|
||||
_states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) =>
|
||||
{
|
||||
_fsql.MapEntityValue(_entityType, item, ov.Value);
|
||||
ov.Time = DateTime.Now;
|
||||
return ov;
|
||||
});
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 清空状态数据
|
||||
/// </summary>
|
||||
public void FlushState()
|
||||
{
|
||||
_states.Clear();
|
||||
}
|
||||
|
||||
#region Utils
|
||||
EntityState CreateEntityState(TEntity data) {
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, false);
|
||||
var state = new EntityState((TEntity)Activator.CreateInstance(_entityType), key);
|
||||
_fsql.MapEntityValue(_entityType, data, state.Value);
|
||||
return state;
|
||||
}
|
||||
bool? ExistsInStates(TEntity data) {
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, false);
|
||||
if (string.IsNullOrEmpty(key)) return null;
|
||||
return _states.ContainsKey(key);
|
||||
}
|
||||
#region Utils
|
||||
EntityState CreateEntityState(TEntity data)
|
||||
{
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, false);
|
||||
var state = new EntityState((TEntity)Activator.CreateInstance(_entityType), key);
|
||||
_fsql.MapEntityValue(_entityType, data, state.Value);
|
||||
return state;
|
||||
}
|
||||
bool? ExistsInStates(TEntity data)
|
||||
{
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, false);
|
||||
if (string.IsNullOrEmpty(key)) return null;
|
||||
return _states.ContainsKey(key);
|
||||
}
|
||||
|
||||
bool CanAdd(IEnumerable<TEntity> data, bool isThrow) {
|
||||
if (data == null) {
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (data.Any() == false) return false;
|
||||
foreach (var s in data) if (CanAdd(s, isThrow) == false) return false;
|
||||
return true;
|
||||
}
|
||||
bool CanAdd(TEntity data, bool isThrow) {
|
||||
if (data == null) {
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (_table.Primarys.Any() == false) {
|
||||
if (isThrow) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, true);
|
||||
if (string.IsNullOrEmpty(key)) {
|
||||
switch (_fsql.Ado.DataType) {
|
||||
case DataType.SqlServer:
|
||||
case DataType.PostgreSQL:
|
||||
return true;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) {
|
||||
return true;
|
||||
}
|
||||
if (isThrow) throw new Exception($"不可添加,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (_states.ContainsKey(key)) {
|
||||
if (isThrow) throw new Exception($"不可添加,已存在于状态管理:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
var idval = _fsql.GetEntityIdentityValueWithPrimary(_entityType, data);
|
||||
if (idval > 0) {
|
||||
if (isThrow) throw new Exception($"不可添加,自增属性有值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool CanAdd(IEnumerable<TEntity> data, bool isThrow)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (data.Any() == false) return false;
|
||||
foreach (var s in data) if (CanAdd(s, isThrow) == false) return false;
|
||||
return true;
|
||||
}
|
||||
bool CanAdd(TEntity data, bool isThrow)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (_table.Primarys.Any() == false)
|
||||
{
|
||||
if (isThrow) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, true);
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
switch (_fsql.Ado.DataType)
|
||||
{
|
||||
case DataType.SqlServer:
|
||||
case DataType.PostgreSQL:
|
||||
return true;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (isThrow) throw new Exception($"不可添加,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_states.ContainsKey(key))
|
||||
{
|
||||
if (isThrow) throw new Exception($"不可添加,已存在于状态管理:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
var idval = _fsql.GetEntityIdentityValueWithPrimary(_entityType, data);
|
||||
if (idval > 0)
|
||||
{
|
||||
if (isThrow) throw new Exception($"不可添加,自增属性有值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CanUpdate(IEnumerable<TEntity> data, bool isThrow) {
|
||||
if (data == null) {
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (data.Any() == false) return false;
|
||||
foreach (var s in data) if (CanUpdate(s, isThrow) == false) return false;
|
||||
return true;
|
||||
}
|
||||
bool CanUpdate(TEntity data, bool isThrow) {
|
||||
if (data == null) {
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (_table.Primarys.Any() == false) {
|
||||
if (isThrow) throw new Exception($"不可更新,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, false);
|
||||
if (string.IsNullOrEmpty(key)) {
|
||||
if (isThrow) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
if (_states.TryGetValue(key, out var tryval) == false) {
|
||||
if (isThrow) throw new Exception($"不可更新,数据未被跟踪,应该先查询 或者 Attach:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool CanUpdate(IEnumerable<TEntity> data, bool isThrow)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (data.Any() == false) return false;
|
||||
foreach (var s in data) if (CanUpdate(s, isThrow) == false) return false;
|
||||
return true;
|
||||
}
|
||||
bool CanUpdate(TEntity data, bool isThrow)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (_table.Primarys.Any() == false)
|
||||
{
|
||||
if (isThrow) throw new Exception($"不可更新,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, false);
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
if (isThrow) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
if (_states.TryGetValue(key, out var tryval) == false)
|
||||
{
|
||||
if (isThrow) throw new Exception($"不可更新,数据未被跟踪,应该先查询 或者 Attach:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CanRemove(IEnumerable<TEntity> data, bool isThrow) {
|
||||
if (data == null) {
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (data.Any() == false) return false;
|
||||
foreach (var s in data) if (CanRemove(s, isThrow) == false) return false;
|
||||
return true;
|
||||
}
|
||||
bool CanRemove(TEntity data, bool isThrow) {
|
||||
if (data == null) {
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (_table.Primarys.Any() == false) {
|
||||
if (isThrow) throw new Exception($"不可删除,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, false);
|
||||
if (string.IsNullOrEmpty(key)) {
|
||||
if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
//if (_states.TryGetValue(key, out var tryval) == false) {
|
||||
// if (isThrow) throw new Exception($"不可删除,数据未被跟踪,应该先查询:{_fsql.GetEntityString(_entityType, data)}");
|
||||
// return false;
|
||||
//}
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
bool CanRemove(IEnumerable<TEntity> data, bool isThrow)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (data.Any() == false) return false;
|
||||
foreach (var s in data) if (CanRemove(s, isThrow) == false) return false;
|
||||
return true;
|
||||
}
|
||||
bool CanRemove(TEntity data, bool isThrow)
|
||||
{
|
||||
if (data == null)
|
||||
{
|
||||
if (isThrow) throw new ArgumentNullException(nameof(data));
|
||||
return false;
|
||||
}
|
||||
if (_table.Primarys.Any() == false)
|
||||
{
|
||||
if (isThrow) throw new Exception($"不可删除,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
var key = _fsql.GetEntityKeyString(_entityType, data, false);
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
return false;
|
||||
}
|
||||
//if (_states.TryGetValue(key, out var tryval) == false) {
|
||||
// if (isThrow) throw new Exception($"不可删除,数据未被跟踪,应该先查询:{_fsql.GetEntityString(_entityType, data)}");
|
||||
// return false;
|
||||
//}
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
@ -6,263 +6,303 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql {
|
||||
partial class DbSet<TEntity> {
|
||||
namespace FreeSql
|
||||
{
|
||||
partial class DbSet<TEntity>
|
||||
{
|
||||
|
||||
Task DbContextExecCommandAsync() {
|
||||
_dicUpdateTimes.Clear();
|
||||
return _ctx.ExecCommandAsync();
|
||||
}
|
||||
Task DbContextExecCommandAsync()
|
||||
{
|
||||
_dicUpdateTimes.Clear();
|
||||
return _ctx.ExecCommandAsync();
|
||||
}
|
||||
|
||||
async Task<int> DbContextBetchAddAsync(EntityState[] adds) {
|
||||
if (adds.Any() == false) return 0;
|
||||
var affrows = await this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrowsAsync();
|
||||
return affrows;
|
||||
}
|
||||
async Task<int> DbContextBetchAddAsync(EntityState[] adds)
|
||||
{
|
||||
if (adds.Any() == false) return 0;
|
||||
var affrows = await this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrowsAsync();
|
||||
return affrows;
|
||||
}
|
||||
|
||||
#region Add
|
||||
async Task AddPrivAsync(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) {
|
||||
await DbContextExecCommandAsync();
|
||||
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
await AddOrUpdateNavigateListAsync(data);
|
||||
} else {
|
||||
await DbContextExecCommandAsync();
|
||||
var newval = (await this.OrmInsert(data).ExecuteInsertedAsync()).First();
|
||||
IncrAffrows(1);
|
||||
_fsql.MapEntityValue(_entityType, newval, data);
|
||||
Attach(newval);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
await AddOrUpdateNavigateListAsync(data);
|
||||
}
|
||||
return;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) {
|
||||
await DbContextExecCommandAsync();
|
||||
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
await AddOrUpdateNavigateListAsync(data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data));
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
await AddOrUpdateNavigateListAsync(data);
|
||||
}
|
||||
public Task AddAsync(TEntity data) => AddPrivAsync(data, true);
|
||||
async public Task AddRangeAsync(IEnumerable<TEntity> data) {
|
||||
if (CanAdd(data, true) == false) return;
|
||||
if (data.ElementAtOrDefault(1) == default(TEntity)) {
|
||||
await AddAsync(data.First());
|
||||
return;
|
||||
}
|
||||
if (_tableIdentitys.Length > 0) {
|
||||
//有自增,马上执行
|
||||
switch (_fsql.Ado.DataType) {
|
||||
case DataType.SqlServer:
|
||||
case DataType.PostgreSQL:
|
||||
await DbContextExecCommandAsync();
|
||||
var rets = await this.OrmInsert(data).ExecuteInsertedAsync();
|
||||
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
|
||||
var idx = 0;
|
||||
foreach (var s in data)
|
||||
_fsql.MapEntityValue(_entityType, rets[idx++], s);
|
||||
IncrAffrows(rets.Count);
|
||||
AttachRange(rets);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
await AddOrUpdateNavigateListAsync(item);
|
||||
return;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
foreach (var s in data)
|
||||
await AddPrivAsync(s, false);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
//进入队列,等待 SaveChanges 时执行
|
||||
foreach (var item in data)
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item));
|
||||
AttachRange(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
await AddOrUpdateNavigateListAsync(item);
|
||||
}
|
||||
}
|
||||
async Task AddOrUpdateNavigateListAsync(TEntity item) {
|
||||
Type itemType = null;
|
||||
foreach (var prop in _table.Properties) {
|
||||
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
|
||||
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
|
||||
var tref = _table.GetTableRef(prop.Key, true);
|
||||
if (tref == null) continue;
|
||||
#region Add
|
||||
async Task AddPrivAsync(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)
|
||||
{
|
||||
await DbContextExecCommandAsync();
|
||||
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
await AddOrUpdateNavigateListAsync(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
await DbContextExecCommandAsync();
|
||||
var newval = (await this.OrmInsert(data).ExecuteInsertedAsync()).First();
|
||||
IncrAffrows(1);
|
||||
_fsql.MapEntityValue(_entityType, newval, data);
|
||||
Attach(newval);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
await AddOrUpdateNavigateListAsync(data);
|
||||
}
|
||||
return;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1)
|
||||
{
|
||||
await DbContextExecCommandAsync();
|
||||
var idtval = await this.OrmInsert(data).ExecuteIdentityAsync();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
await AddOrUpdateNavigateListAsync(data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data));
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
await AddOrUpdateNavigateListAsync(data);
|
||||
}
|
||||
public Task AddAsync(TEntity data) => AddPrivAsync(data, true);
|
||||
async public Task AddRangeAsync(IEnumerable<TEntity> data)
|
||||
{
|
||||
if (CanAdd(data, true) == false) return;
|
||||
if (data.ElementAtOrDefault(1) == default(TEntity))
|
||||
{
|
||||
await AddAsync(data.First());
|
||||
return;
|
||||
}
|
||||
if (_tableIdentitys.Length > 0)
|
||||
{
|
||||
//有自增,马上执行
|
||||
switch (_fsql.Ado.DataType)
|
||||
{
|
||||
case DataType.SqlServer:
|
||||
case DataType.PostgreSQL:
|
||||
await DbContextExecCommandAsync();
|
||||
var rets = await this.OrmInsert(data).ExecuteInsertedAsync();
|
||||
if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配");
|
||||
var idx = 0;
|
||||
foreach (var s in data)
|
||||
_fsql.MapEntityValue(_entityType, rets[idx++], s);
|
||||
IncrAffrows(rets.Count);
|
||||
AttachRange(rets);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
await AddOrUpdateNavigateListAsync(item);
|
||||
return;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
foreach (var s in data)
|
||||
await AddPrivAsync(s, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//进入队列,等待 SaveChanges 时执行
|
||||
foreach (var item in data)
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item));
|
||||
AttachRange(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
await AddOrUpdateNavigateListAsync(item);
|
||||
}
|
||||
}
|
||||
async Task AddOrUpdateNavigateListAsync(TEntity item)
|
||||
{
|
||||
Type itemType = null;
|
||||
foreach (var prop in _table.Properties)
|
||||
{
|
||||
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
|
||||
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
|
||||
var tref = _table.GetTableRef(prop.Key, true);
|
||||
if (tref == null) continue;
|
||||
|
||||
switch (tref.RefType) {
|
||||
case Internal.Model.TableRefType.OneToOne:
|
||||
case Internal.Model.TableRefType.ManyToOne:
|
||||
case Internal.Model.TableRefType.ManyToMany:
|
||||
continue;
|
||||
case Internal.Model.TableRefType.OneToMany:
|
||||
if (itemType == null) itemType = item.GetType();
|
||||
if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
|
||||
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, System.Reflection.FieldInfo>()).GetOrAdd(prop.Key, propName =>
|
||||
_table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance));
|
||||
if (lazyField != null) {
|
||||
var lazyFieldValue = (bool)lazyField.GetValue(item);
|
||||
if (lazyFieldValue == false) continue;
|
||||
}
|
||||
}
|
||||
var propVal = prop.Value.GetValue(item);
|
||||
var propValEach = propVal as IEnumerable;
|
||||
if (propValEach == null) continue;
|
||||
object dbset = null;
|
||||
System.Reflection.MethodInfo dbsetAddOrUpdate = null;
|
||||
foreach (var propValItem in propValEach) {
|
||||
if (dbset == null) {
|
||||
dbset = _ctx.Set(tref.RefEntityType);
|
||||
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEntityType });
|
||||
}
|
||||
for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
|
||||
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
|
||||
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
|
||||
}
|
||||
Task task = dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }) as Task;
|
||||
await task;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
switch (tref.RefType)
|
||||
{
|
||||
case Internal.Model.TableRefType.OneToOne:
|
||||
case Internal.Model.TableRefType.ManyToOne:
|
||||
case Internal.Model.TableRefType.ManyToMany:
|
||||
continue;
|
||||
case Internal.Model.TableRefType.OneToMany:
|
||||
if (itemType == null) itemType = item.GetType();
|
||||
if (_table.TypeLazy != null && itemType == _table.TypeLazy)
|
||||
{
|
||||
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, System.Reflection.FieldInfo>()).GetOrAdd(prop.Key, propName =>
|
||||
_table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance));
|
||||
if (lazyField != null)
|
||||
{
|
||||
var lazyFieldValue = (bool)lazyField.GetValue(item);
|
||||
if (lazyFieldValue == false) continue;
|
||||
}
|
||||
}
|
||||
var propVal = prop.Value.GetValue(item);
|
||||
var propValEach = propVal as IEnumerable;
|
||||
if (propValEach == null) continue;
|
||||
object dbset = null;
|
||||
System.Reflection.MethodInfo dbsetAddOrUpdate = null;
|
||||
foreach (var propValItem in propValEach)
|
||||
{
|
||||
if (dbset == null)
|
||||
{
|
||||
dbset = _ctx.Set(tref.RefEntityType);
|
||||
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEntityType });
|
||||
}
|
||||
for (var colidx = 0; colidx < tref.Columns.Count; colidx++)
|
||||
{
|
||||
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
|
||||
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
|
||||
}
|
||||
Task task = dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }) as Task;
|
||||
await task;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region UpdateAsync
|
||||
Task<int> DbContextBetchUpdateAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, false);
|
||||
Task<int> DbContextBetchUpdateNowAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, true);
|
||||
async Task<int> DbContextBetchUpdatePrivAsync(EntityState[] ups, bool isLiveUpdate) {
|
||||
if (ups.Any() == false) return 0;
|
||||
var uplst1 = ups[ups.Length - 1];
|
||||
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
|
||||
#region UpdateAsync
|
||||
Task<int> DbContextBetchUpdateAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, false);
|
||||
Task<int> DbContextBetchUpdateNowAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, true);
|
||||
async Task<int> DbContextBetchUpdatePrivAsync(EntityState[] ups, bool isLiveUpdate)
|
||||
{
|
||||
if (ups.Any() == false) return 0;
|
||||
var uplst1 = ups[ups.Length - 1];
|
||||
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
|
||||
|
||||
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
|
||||
var lstval2 = default(EntityState);
|
||||
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}");
|
||||
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
|
||||
var lstval2 = default(EntityState);
|
||||
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}");
|
||||
|
||||
var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true);
|
||||
var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null;
|
||||
var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true);
|
||||
var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null;
|
||||
|
||||
List<EntityState> data = null;
|
||||
string[] cuig = null;
|
||||
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
|
||||
//最后一个不保存
|
||||
data = ups.ToList();
|
||||
data.RemoveAt(ups.Length - 1);
|
||||
cuig = cuig2;
|
||||
} else if (isLiveUpdate) {
|
||||
//立即保存
|
||||
data = ups.ToList();
|
||||
cuig = cuig1;
|
||||
}
|
||||
List<EntityState> data = null;
|
||||
string[] cuig = null;
|
||||
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0)
|
||||
{
|
||||
//最后一个不保存
|
||||
data = ups.ToList();
|
||||
data.RemoveAt(ups.Length - 1);
|
||||
cuig = cuig2;
|
||||
}
|
||||
else if (isLiveUpdate)
|
||||
{
|
||||
//立即保存
|
||||
data = ups.ToList();
|
||||
cuig = cuig1;
|
||||
}
|
||||
|
||||
if (data?.Count > 0) {
|
||||
if (data?.Count > 0)
|
||||
{
|
||||
|
||||
if (cuig.Length == _table.Columns.Count)
|
||||
return ups.Length == data.Count ? -998 : -997;
|
||||
if (cuig.Length == _table.Columns.Count)
|
||||
return ups.Length == data.Count ? -998 : -997;
|
||||
|
||||
var updateSource = data.Select(a => a.Value).ToArray();
|
||||
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
|
||||
var updateSource = data.Select(a => a.Value).ToArray();
|
||||
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
|
||||
|
||||
var affrows = await update.ExecuteAffrowsAsync();
|
||||
var affrows = await update.ExecuteAffrowsAsync();
|
||||
|
||||
foreach (var newval in data) {
|
||||
if (_states.TryGetValue(newval.Key, out var tryold))
|
||||
_fsql.MapEntityValue(_entityType, newval.Value, tryold.Value);
|
||||
if (newval.OldValue != null)
|
||||
_fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue);
|
||||
}
|
||||
return affrows;
|
||||
}
|
||||
foreach (var newval in data)
|
||||
{
|
||||
if (_states.TryGetValue(newval.Key, out var tryold))
|
||||
_fsql.MapEntityValue(_entityType, newval.Value, tryold.Value);
|
||||
if (newval.OldValue != null)
|
||||
_fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue);
|
||||
}
|
||||
return affrows;
|
||||
}
|
||||
|
||||
//等待下次对比再保存
|
||||
return 0;
|
||||
}
|
||||
async public Task UpdateAsync(TEntity data) {
|
||||
var exists = ExistsInStates(data);
|
||||
if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
if (exists == false) {
|
||||
var olddata = await OrmSelect(data).FirstAsync();
|
||||
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}");
|
||||
}
|
||||
//等待下次对比再保存
|
||||
return 0;
|
||||
}
|
||||
async public Task UpdateAsync(TEntity data)
|
||||
{
|
||||
var exists = ExistsInStates(data);
|
||||
if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
if (exists == false)
|
||||
{
|
||||
var olddata = await OrmSelect(data).FirstAsync();
|
||||
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}");
|
||||
}
|
||||
|
||||
await UpdateRangePrivAsync(new[] { data }, true);
|
||||
}
|
||||
public Task UpdateRangeAsync(IEnumerable<TEntity> data) => UpdateRangePrivAsync(data, true);
|
||||
async Task UpdateRangePrivAsync(IEnumerable<TEntity> data, bool isCheck) {
|
||||
if (CanUpdate(data, true) == false) return;
|
||||
foreach (var item in data) {
|
||||
if (_dicUpdateTimes.ContainsKey(item))
|
||||
await DbContextExecCommandAsync();
|
||||
_dicUpdateTimes.Add(item, 1);
|
||||
await UpdateRangePrivAsync(new[] { data }, true);
|
||||
}
|
||||
public Task UpdateRangeAsync(IEnumerable<TEntity> data) => UpdateRangePrivAsync(data, true);
|
||||
async Task UpdateRangePrivAsync(IEnumerable<TEntity> data, bool isCheck)
|
||||
{
|
||||
if (CanUpdate(data, true) == false) return;
|
||||
foreach (var item in data)
|
||||
{
|
||||
if (_dicUpdateTimes.ContainsKey(item))
|
||||
await DbContextExecCommandAsync();
|
||||
_dicUpdateTimes.Add(item, 1);
|
||||
|
||||
var state = CreateEntityState(item);
|
||||
state.OldValue = item;
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state);
|
||||
}
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
await AddOrUpdateNavigateListAsync(item);
|
||||
}
|
||||
#endregion
|
||||
var state = CreateEntityState(item);
|
||||
state.OldValue = item;
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state);
|
||||
}
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
await AddOrUpdateNavigateListAsync(item);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region RemoveAsync
|
||||
async Task<int> DbContextBetchRemoveAsync(EntityState[] dels) {
|
||||
if (dels.Any() == false) return 0;
|
||||
var affrows = await this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrowsAsync();
|
||||
return Math.Max(dels.Length, affrows);
|
||||
}
|
||||
#endregion
|
||||
#region RemoveAsync
|
||||
async Task<int> DbContextBetchRemoveAsync(EntityState[] dels)
|
||||
{
|
||||
if (dels.Any() == false) return 0;
|
||||
var affrows = await this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrowsAsync();
|
||||
return Math.Max(dels.Length, affrows);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region AddOrUpdateAsync
|
||||
async public Task AddOrUpdateAsync(TEntity data) {
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
#region AddOrUpdateAsync
|
||||
async public Task AddOrUpdateAsync(TEntity data)
|
||||
{
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
|
||||
var flagExists = ExistsInStates(data);
|
||||
if (flagExists == false) {
|
||||
var olddata = await OrmSelect(data).FirstAsync();
|
||||
if (olddata == null) flagExists = false;
|
||||
}
|
||||
var flagExists = ExistsInStates(data);
|
||||
if (flagExists == false)
|
||||
{
|
||||
var olddata = await OrmSelect(data).FirstAsync();
|
||||
if (olddata == null) flagExists = false;
|
||||
}
|
||||
|
||||
if (flagExists == true && CanUpdate(data, false)) {
|
||||
await DbContextExecCommandAsync();
|
||||
var affrows = _ctx._affrows;
|
||||
await UpdateRangePrivAsync(new[] { data }, false);
|
||||
await DbContextExecCommandAsync();
|
||||
affrows = _ctx._affrows - affrows;
|
||||
if (affrows > 0) return;
|
||||
}
|
||||
if (CanAdd(data, false)) {
|
||||
_fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data);
|
||||
await AddPrivAsync(data, false);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
if (flagExists == true && CanUpdate(data, false))
|
||||
{
|
||||
await DbContextExecCommandAsync();
|
||||
var affrows = _ctx._affrows;
|
||||
await UpdateRangePrivAsync(new[] { data }, false);
|
||||
await DbContextExecCommandAsync();
|
||||
affrows = _ctx._affrows - affrows;
|
||||
if (affrows > 0) return;
|
||||
}
|
||||
if (CanAdd(data, false))
|
||||
{
|
||||
_fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data);
|
||||
await AddPrivAsync(data, false);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
@ -6,300 +6,344 @@ using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace FreeSql {
|
||||
partial class DbSet<TEntity> {
|
||||
namespace FreeSql
|
||||
{
|
||||
partial class DbSet<TEntity>
|
||||
{
|
||||
|
||||
void DbContextExecCommand() {
|
||||
_dicUpdateTimes.Clear();
|
||||
_ctx.ExecCommand();
|
||||
}
|
||||
void DbContextExecCommand()
|
||||
{
|
||||
_dicUpdateTimes.Clear();
|
||||
_ctx.ExecCommand();
|
||||
}
|
||||
|
||||
int DbContextBetchAdd(EntityState[] adds) {
|
||||
if (adds.Any() == false) return 0;
|
||||
var affrows = this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrows();
|
||||
return affrows;
|
||||
}
|
||||
int DbContextBetchAdd(EntityState[] adds)
|
||||
{
|
||||
if (adds.Any() == false) return 0;
|
||||
var affrows = this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrows();
|
||||
return affrows;
|
||||
}
|
||||
|
||||
#region Add
|
||||
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) {
|
||||
DbContextExecCommand();
|
||||
var idtval = this.OrmInsert(data).ExecuteIdentity();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
AddOrUpdateNavigateList(data);
|
||||
} else {
|
||||
DbContextExecCommand();
|
||||
var newval = this.OrmInsert(data).ExecuteInserted().First();
|
||||
IncrAffrows(1);
|
||||
_fsql.MapEntityValue(_entityType, newval, data);
|
||||
Attach(newval);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
AddOrUpdateNavigateList(data);
|
||||
}
|
||||
return;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
if (_tableIdentitys.Length == 1) {
|
||||
DbContextExecCommand();
|
||||
var idtval = this.OrmInsert(data).ExecuteIdentity();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
AddOrUpdateNavigateList(data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data));
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
AddOrUpdateNavigateList(data);
|
||||
}
|
||||
/// <summary>
|
||||
/// 添加
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void Add(TEntity data) => AddPriv(data, true);
|
||||
public void AddRange(IEnumerable<TEntity> data) {
|
||||
if (CanAdd(data, true) == false) return;
|
||||
if (data.ElementAtOrDefault(1) == default(TEntity)) {
|
||||
Add(data.First());
|
||||
return;
|
||||
}
|
||||
if (_tableIdentitys.Length > 0) {
|
||||
//有自增,马上执行
|
||||
switch (_fsql.Ado.DataType) {
|
||||
case DataType.SqlServer:
|
||||
case DataType.PostgreSQL:
|
||||
DbContextExecCommand();
|
||||
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(_entityType, rets[idx++], s);
|
||||
IncrAffrows(rets.Count);
|
||||
AttachRange(rets);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
AddOrUpdateNavigateList(item);
|
||||
return;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
foreach (var s in data)
|
||||
AddPriv(s, false);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
//进入队列,等待 SaveChanges 时执行
|
||||
foreach (var item in data)
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item));
|
||||
AttachRange(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
AddOrUpdateNavigateList(item);
|
||||
}
|
||||
}
|
||||
static ConcurrentDictionary<Type, ConcurrentDictionary<string, FieldInfo>> _dicLazyIsSetField = new ConcurrentDictionary<Type, ConcurrentDictionary<string, FieldInfo>>();
|
||||
void AddOrUpdateNavigateList(TEntity item) {
|
||||
Type itemType = null;
|
||||
foreach (var prop in _table.Properties) {
|
||||
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
|
||||
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
|
||||
#region Add
|
||||
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)
|
||||
{
|
||||
DbContextExecCommand();
|
||||
var idtval = this.OrmInsert(data).ExecuteIdentity();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
AddOrUpdateNavigateList(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
DbContextExecCommand();
|
||||
var newval = this.OrmInsert(data).ExecuteInserted().First();
|
||||
IncrAffrows(1);
|
||||
_fsql.MapEntityValue(_entityType, newval, data);
|
||||
Attach(newval);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
AddOrUpdateNavigateList(data);
|
||||
}
|
||||
return;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
if (_tableIdentitys.Length == 1)
|
||||
{
|
||||
DbContextExecCommand();
|
||||
var idtval = this.OrmInsert(data).ExecuteIdentity();
|
||||
IncrAffrows(1);
|
||||
_fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval);
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
AddOrUpdateNavigateList(data);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data));
|
||||
Attach(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
AddOrUpdateNavigateList(data);
|
||||
}
|
||||
/// <summary>
|
||||
/// 添加
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void Add(TEntity data) => AddPriv(data, true);
|
||||
public void AddRange(IEnumerable<TEntity> data)
|
||||
{
|
||||
if (CanAdd(data, true) == false) return;
|
||||
if (data.ElementAtOrDefault(1) == default(TEntity))
|
||||
{
|
||||
Add(data.First());
|
||||
return;
|
||||
}
|
||||
if (_tableIdentitys.Length > 0)
|
||||
{
|
||||
//有自增,马上执行
|
||||
switch (_fsql.Ado.DataType)
|
||||
{
|
||||
case DataType.SqlServer:
|
||||
case DataType.PostgreSQL:
|
||||
DbContextExecCommand();
|
||||
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(_entityType, rets[idx++], s);
|
||||
IncrAffrows(rets.Count);
|
||||
AttachRange(rets);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
AddOrUpdateNavigateList(item);
|
||||
return;
|
||||
case DataType.MySql:
|
||||
case DataType.Oracle:
|
||||
case DataType.Sqlite:
|
||||
foreach (var s in data)
|
||||
AddPriv(s, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//进入队列,等待 SaveChanges 时执行
|
||||
foreach (var item in data)
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item));
|
||||
AttachRange(data);
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
AddOrUpdateNavigateList(item);
|
||||
}
|
||||
}
|
||||
static ConcurrentDictionary<Type, ConcurrentDictionary<string, FieldInfo>> _dicLazyIsSetField = new ConcurrentDictionary<Type, ConcurrentDictionary<string, FieldInfo>>();
|
||||
void AddOrUpdateNavigateList(TEntity item)
|
||||
{
|
||||
Type itemType = null;
|
||||
foreach (var prop in _table.Properties)
|
||||
{
|
||||
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
|
||||
if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;
|
||||
|
||||
object propVal = null;
|
||||
object propVal = null;
|
||||
|
||||
if (itemType == null) itemType = item.GetType();
|
||||
if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
|
||||
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, FieldInfo>()).GetOrAdd(prop.Key, propName =>
|
||||
_table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance));
|
||||
if (lazyField != null) {
|
||||
var lazyFieldValue = (bool)lazyField.GetValue(item);
|
||||
if (lazyFieldValue == false) continue;
|
||||
}
|
||||
propVal = prop.Value.GetValue(item);
|
||||
} else {
|
||||
propVal = prop.Value.GetValue(item);
|
||||
if (propVal == null) continue;
|
||||
}
|
||||
if (itemType == null) itemType = item.GetType();
|
||||
if (_table.TypeLazy != null && itemType == _table.TypeLazy)
|
||||
{
|
||||
var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, FieldInfo>()).GetOrAdd(prop.Key, propName =>
|
||||
_table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance));
|
||||
if (lazyField != null)
|
||||
{
|
||||
var lazyFieldValue = (bool)lazyField.GetValue(item);
|
||||
if (lazyFieldValue == false) continue;
|
||||
}
|
||||
propVal = prop.Value.GetValue(item);
|
||||
}
|
||||
else
|
||||
{
|
||||
propVal = prop.Value.GetValue(item);
|
||||
if (propVal == null) continue;
|
||||
}
|
||||
|
||||
var tref = _table.GetTableRef(prop.Key, true);
|
||||
if (tref == null) continue;
|
||||
var tref = _table.GetTableRef(prop.Key, true);
|
||||
if (tref == null) continue;
|
||||
|
||||
switch(tref.RefType) {
|
||||
case Internal.Model.TableRefType.OneToOne:
|
||||
case Internal.Model.TableRefType.ManyToOne:
|
||||
case Internal.Model.TableRefType.ManyToMany:
|
||||
continue;
|
||||
case Internal.Model.TableRefType.OneToMany:
|
||||
var propValEach = propVal as IEnumerable;
|
||||
if (propValEach == null) continue;
|
||||
object dbset = null;
|
||||
MethodInfo dbsetAddOrUpdate = null;
|
||||
foreach (var propValItem in propValEach) {
|
||||
if (dbset == null) {
|
||||
dbset = _ctx.Set(tref.RefEntityType);
|
||||
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEntityType });
|
||||
}
|
||||
for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
|
||||
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
|
||||
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
|
||||
}
|
||||
dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem });
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
switch (tref.RefType)
|
||||
{
|
||||
case Internal.Model.TableRefType.OneToOne:
|
||||
case Internal.Model.TableRefType.ManyToOne:
|
||||
case Internal.Model.TableRefType.ManyToMany:
|
||||
continue;
|
||||
case Internal.Model.TableRefType.OneToMany:
|
||||
var propValEach = propVal as IEnumerable;
|
||||
if (propValEach == null) continue;
|
||||
object dbset = null;
|
||||
MethodInfo dbsetAddOrUpdate = null;
|
||||
foreach (var propValItem in propValEach)
|
||||
{
|
||||
if (dbset == null)
|
||||
{
|
||||
dbset = _ctx.Set(tref.RefEntityType);
|
||||
dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEntityType });
|
||||
}
|
||||
for (var colidx = 0; colidx < tref.Columns.Count; colidx++)
|
||||
{
|
||||
tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
|
||||
.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
|
||||
}
|
||||
dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem });
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Update
|
||||
int DbContextBetchUpdate(EntityState[] ups) => DbContextBetchUpdatePriv(ups, false);
|
||||
int DbContextBetchUpdateNow(EntityState[] ups) => DbContextBetchUpdatePriv(ups, true);
|
||||
int DbContextBetchUpdatePriv(EntityState[] ups, bool isLiveUpdate) {
|
||||
if (ups.Any() == false) return 0;
|
||||
var uplst1 = ups[ups.Length - 1];
|
||||
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
|
||||
#region Update
|
||||
int DbContextBetchUpdate(EntityState[] ups) => DbContextBetchUpdatePriv(ups, false);
|
||||
int DbContextBetchUpdateNow(EntityState[] ups) => DbContextBetchUpdatePriv(ups, true);
|
||||
int DbContextBetchUpdatePriv(EntityState[] ups, bool isLiveUpdate)
|
||||
{
|
||||
if (ups.Any() == false) return 0;
|
||||
var uplst1 = ups[ups.Length - 1];
|
||||
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
|
||||
|
||||
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
|
||||
var lstval2 = default(EntityState);
|
||||
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}");
|
||||
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
|
||||
var lstval2 = default(EntityState);
|
||||
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}");
|
||||
|
||||
var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true);
|
||||
var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null;
|
||||
var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true);
|
||||
var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null;
|
||||
|
||||
List<EntityState> data = null;
|
||||
string[] cuig = null;
|
||||
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
|
||||
//最后一个不保存
|
||||
data = ups.ToList();
|
||||
data.RemoveAt(ups.Length - 1);
|
||||
cuig = cuig2;
|
||||
} else if (isLiveUpdate) {
|
||||
//立即保存
|
||||
data = ups.ToList();
|
||||
cuig = cuig1;
|
||||
}
|
||||
List<EntityState> data = null;
|
||||
string[] cuig = null;
|
||||
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0)
|
||||
{
|
||||
//最后一个不保存
|
||||
data = ups.ToList();
|
||||
data.RemoveAt(ups.Length - 1);
|
||||
cuig = cuig2;
|
||||
}
|
||||
else if (isLiveUpdate)
|
||||
{
|
||||
//立即保存
|
||||
data = ups.ToList();
|
||||
cuig = cuig1;
|
||||
}
|
||||
|
||||
if (data?.Count > 0) {
|
||||
if (data?.Count > 0)
|
||||
{
|
||||
|
||||
if (cuig.Length == _table.Columns.Count)
|
||||
return ups.Length == data.Count ? -998 : -997;
|
||||
if (cuig.Length == _table.Columns.Count)
|
||||
return ups.Length == data.Count ? -998 : -997;
|
||||
|
||||
var updateSource = data.Select(a => a.Value).ToArray();
|
||||
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
|
||||
var updateSource = data.Select(a => a.Value).ToArray();
|
||||
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
|
||||
|
||||
var affrows = update.ExecuteAffrows();
|
||||
var affrows = update.ExecuteAffrows();
|
||||
|
||||
foreach (var newval in data) {
|
||||
if (_states.TryGetValue(newval.Key, out var tryold))
|
||||
_fsql.MapEntityValue(_entityType, newval.Value, tryold.Value);
|
||||
if (newval.OldValue != null)
|
||||
_fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue);
|
||||
}
|
||||
return affrows;
|
||||
}
|
||||
foreach (var newval in data)
|
||||
{
|
||||
if (_states.TryGetValue(newval.Key, out var tryold))
|
||||
_fsql.MapEntityValue(_entityType, newval.Value, tryold.Value);
|
||||
if (newval.OldValue != null)
|
||||
_fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue);
|
||||
}
|
||||
return affrows;
|
||||
}
|
||||
|
||||
//等待下次对比再保存
|
||||
return 0;
|
||||
}
|
||||
//等待下次对比再保存
|
||||
return 0;
|
||||
}
|
||||
|
||||
Dictionary<TEntity, byte> _dicUpdateTimes = new Dictionary<TEntity, byte>();
|
||||
/// <summary>
|
||||
/// 更新
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void Update(TEntity data) {
|
||||
var exists = ExistsInStates(data);
|
||||
if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
if (exists == false) {
|
||||
var olddata = OrmSelect(data).First();
|
||||
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}");
|
||||
}
|
||||
Dictionary<TEntity, byte> _dicUpdateTimes = new Dictionary<TEntity, byte>();
|
||||
/// <summary>
|
||||
/// 更新
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void Update(TEntity data)
|
||||
{
|
||||
var exists = ExistsInStates(data);
|
||||
if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}");
|
||||
if (exists == false)
|
||||
{
|
||||
var olddata = OrmSelect(data).First();
|
||||
if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}");
|
||||
}
|
||||
|
||||
UpdateRangePriv(new[] { data }, true);
|
||||
}
|
||||
public void UpdateRange(IEnumerable<TEntity> data) => UpdateRangePriv(data, true);
|
||||
void UpdateRangePriv(IEnumerable<TEntity> data, bool isCheck) {
|
||||
if (CanUpdate(data, true) == false) return;
|
||||
foreach (var item in data) {
|
||||
if (_dicUpdateTimes.ContainsKey(item))
|
||||
DbContextExecCommand();
|
||||
_dicUpdateTimes.Add(item, 1);
|
||||
UpdateRangePriv(new[] { data }, true);
|
||||
}
|
||||
public void UpdateRange(IEnumerable<TEntity> data) => UpdateRangePriv(data, true);
|
||||
void UpdateRangePriv(IEnumerable<TEntity> data, bool isCheck)
|
||||
{
|
||||
if (CanUpdate(data, true) == false) return;
|
||||
foreach (var item in data)
|
||||
{
|
||||
if (_dicUpdateTimes.ContainsKey(item))
|
||||
DbContextExecCommand();
|
||||
_dicUpdateTimes.Add(item, 1);
|
||||
|
||||
var state = CreateEntityState(item);
|
||||
state.OldValue = item;
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state);
|
||||
}
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
AddOrUpdateNavigateList(item);
|
||||
}
|
||||
#endregion
|
||||
var state = CreateEntityState(item);
|
||||
state.OldValue = item;
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state);
|
||||
}
|
||||
if (_ctx.Options.EnableAddOrUpdateNavigateList)
|
||||
foreach (var item in data)
|
||||
AddOrUpdateNavigateList(item);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Remove
|
||||
int DbContextBetchRemove(EntityState[] dels) {
|
||||
if (dels.Any() == false) return 0;
|
||||
var affrows = this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrows();
|
||||
return Math.Max(dels.Length, affrows);
|
||||
}
|
||||
#region Remove
|
||||
int DbContextBetchRemove(EntityState[] dels)
|
||||
{
|
||||
if (dels.Any() == false) return 0;
|
||||
var affrows = this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrows();
|
||||
return Math.Max(dels.Length, affrows);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void Remove(TEntity data) => RemoveRange(new[] { data });
|
||||
public void RemoveRange(IEnumerable<TEntity> data) {
|
||||
if (CanRemove(data, true) == false) return;
|
||||
foreach (var item in data) {
|
||||
var state = CreateEntityState(item);
|
||||
_states.TryRemove(state.Key, out var trystate);
|
||||
_fsql.ClearEntityPrimaryValueWithIdentityAndGuid(_entityType, item);
|
||||
/// <summary>
|
||||
/// 删除
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void Remove(TEntity data) => RemoveRange(new[] { data });
|
||||
public void RemoveRange(IEnumerable<TEntity> data)
|
||||
{
|
||||
if (CanRemove(data, true) == false) return;
|
||||
foreach (var item in data)
|
||||
{
|
||||
var state = CreateEntityState(item);
|
||||
_states.TryRemove(state.Key, out var trystate);
|
||||
_fsql.ClearEntityPrimaryValueWithIdentityAndGuid(_entityType, item);
|
||||
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Delete, state);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
EnqueueToDbContext(DbContext.ExecCommandInfoType.Delete, state);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region AddOrUpdate
|
||||
/// <summary>
|
||||
/// 添加或更新
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void AddOrUpdate(TEntity data) {
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
#region AddOrUpdate
|
||||
/// <summary>
|
||||
/// 添加或更新
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public void AddOrUpdate(TEntity data)
|
||||
{
|
||||
if (data == null) throw new ArgumentNullException(nameof(data));
|
||||
if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}");
|
||||
|
||||
var flagExists = ExistsInStates(data);
|
||||
if (flagExists == false) {
|
||||
var olddata = OrmSelect(data).First();
|
||||
if (olddata == null) flagExists = false;
|
||||
}
|
||||
var flagExists = ExistsInStates(data);
|
||||
if (flagExists == false)
|
||||
{
|
||||
var olddata = OrmSelect(data).First();
|
||||
if (olddata == null) flagExists = false;
|
||||
}
|
||||
|
||||
if (flagExists == true && CanUpdate(data, false)) {
|
||||
DbContextExecCommand();
|
||||
var affrows = _ctx._affrows;
|
||||
UpdateRangePriv(new[] { data }, false);
|
||||
DbContextExecCommand();
|
||||
affrows = _ctx._affrows - affrows;
|
||||
if (affrows > 0) return;
|
||||
}
|
||||
if (CanAdd(data, false)) {
|
||||
_fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data);
|
||||
AddPriv(data, false);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
if (flagExists == true && CanUpdate(data, false))
|
||||
{
|
||||
DbContextExecCommand();
|
||||
var affrows = _ctx._affrows;
|
||||
UpdateRangePriv(new[] { data }, false);
|
||||
DbContextExecCommand();
|
||||
affrows = _ctx._affrows - affrows;
|
||||
if (affrows > 0) return;
|
||||
}
|
||||
if (CanAdd(data, false))
|
||||
{
|
||||
_fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data);
|
||||
AddPriv(data, false);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
@ -3,30 +3,35 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
|
||||
namespace FreeSql {
|
||||
public static class DbContextDependencyInjection {
|
||||
namespace FreeSql
|
||||
{
|
||||
public static class DbContextDependencyInjection
|
||||
{
|
||||
|
||||
public static IServiceCollection AddFreeDbContext<TDbContext>(this IServiceCollection services, Action<DbContextOptionsBuilder> options) where TDbContext : DbContext {
|
||||
public static IServiceCollection AddFreeDbContext<TDbContext>(this IServiceCollection services, Action<DbContextOptionsBuilder> options) where TDbContext : DbContext
|
||||
{
|
||||
|
||||
services.AddScoped<TDbContext>(sp => {
|
||||
var ctx = Activator.CreateInstance<TDbContext>();
|
||||
services.AddScoped<TDbContext>(sp =>
|
||||
{
|
||||
var ctx = Activator.CreateInstance<TDbContext>();
|
||||
|
||||
if (ctx._orm == null) {
|
||||
var builder = new DbContextOptionsBuilder();
|
||||
options(builder);
|
||||
ctx._orm = builder._fsql;
|
||||
if (ctx._orm == null)
|
||||
{
|
||||
var builder = new DbContextOptionsBuilder();
|
||||
options(builder);
|
||||
ctx._orm = builder._fsql;
|
||||
|
||||
if (ctx._orm == null)
|
||||
throw new Exception("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
|
||||
if (ctx._orm == null)
|
||||
throw new Exception("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
|
||||
|
||||
ctx.InitPropSets();
|
||||
}
|
||||
ctx.InitPropSets();
|
||||
}
|
||||
|
||||
return ctx;
|
||||
});
|
||||
return ctx;
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
@ -2,37 +2,41 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
public static class FreeSqlDbContextExtenssions {
|
||||
public static class FreeSqlDbContextExtenssions
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 创建普通数据上下文档对象
|
||||
/// </summary>
|
||||
/// <param name="that"></param>
|
||||
/// <returns></returns>
|
||||
public static DbContext CreateDbContext(this IFreeSql that) {
|
||||
return new FreeContext(that);
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建普通数据上下文档对象
|
||||
/// </summary>
|
||||
/// <param name="that"></param>
|
||||
/// <returns></returns>
|
||||
public static DbContext CreateDbContext(this IFreeSql that)
|
||||
{
|
||||
return new FreeContext(that);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 不跟踪查询的实体数据(在不需要更新其数据时使用),可提长查询性能
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="select"></param>
|
||||
/// <returns></returns>
|
||||
public static ISelect<T> NoTracking<T>(this ISelect<T> select) where T : class {
|
||||
return select.TrackToList(null);
|
||||
}
|
||||
/// <summary>
|
||||
/// 不跟踪查询的实体数据(在不需要更新其数据时使用),可提长查询性能
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="select"></param>
|
||||
/// <returns></returns>
|
||||
public static ISelect<T> NoTracking<T>(this ISelect<T> select) where T : class
|
||||
{
|
||||
return select.TrackToList(null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置 DbContext 选项设置
|
||||
/// </summary>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="options"></param>
|
||||
public static void SetDbContextOptions(this IFreeSql that, Action<DbContextOptions> options) {
|
||||
if (options == null) return;
|
||||
var cfg = _dicSetDbContextOptions.GetOrAdd(that, t => new DbContextOptions());
|
||||
options(cfg);
|
||||
_dicSetDbContextOptions.AddOrUpdate(that, cfg, (t, o) => cfg);
|
||||
}
|
||||
internal static ConcurrentDictionary<IFreeSql, DbContextOptions> _dicSetDbContextOptions = new ConcurrentDictionary<IFreeSql, DbContextOptions>();
|
||||
/// <summary>
|
||||
/// 设置 DbContext 选项设置
|
||||
/// </summary>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="options"></param>
|
||||
public static void SetDbContextOptions(this IFreeSql that, Action<DbContextOptions> options)
|
||||
{
|
||||
if (options == null) return;
|
||||
var cfg = _dicSetDbContextOptions.GetOrAdd(that, t => new DbContextOptions());
|
||||
options(cfg);
|
||||
_dicSetDbContextOptions.AddOrUpdate(that, cfg, (t, o) => cfg);
|
||||
}
|
||||
internal static ConcurrentDictionary<IFreeSql, DbContextOptions> _dicSetDbContextOptions = new ConcurrentDictionary<IFreeSql, DbContextOptions>();
|
||||
}
|
@ -3,60 +3,69 @@ using System.Collections.Concurrent;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql {
|
||||
internal class RepositoryDbContext : DbContext {
|
||||
namespace FreeSql
|
||||
{
|
||||
internal class RepositoryDbContext : DbContext
|
||||
{
|
||||
|
||||
protected IBaseRepository _repos;
|
||||
public RepositoryDbContext(IFreeSql orm, IBaseRepository repos) : base() {
|
||||
_orm = orm;
|
||||
_repos = repos;
|
||||
_isUseUnitOfWork = false;
|
||||
_uowPriv = _repos.UnitOfWork;
|
||||
}
|
||||
protected IBaseRepository _repos;
|
||||
public RepositoryDbContext(IFreeSql orm, IBaseRepository repos) : base()
|
||||
{
|
||||
_orm = orm;
|
||||
_repos = repos;
|
||||
_isUseUnitOfWork = false;
|
||||
_uowPriv = _repos.UnitOfWork;
|
||||
}
|
||||
|
||||
|
||||
static ConcurrentDictionary<Type, FieldInfo> _dicGetRepositoryDbField = new ConcurrentDictionary<Type, FieldInfo>();
|
||||
static FieldInfo GetRepositoryDbField(Type type) => _dicGetRepositoryDbField.GetOrAdd(type, tp => typeof(BaseRepository<,>).MakeGenericType(tp, typeof(int)).GetField("_dbPriv", BindingFlags.Instance | BindingFlags.NonPublic));
|
||||
public override IDbSet Set(Type entityType) {
|
||||
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
|
||||
static ConcurrentDictionary<Type, FieldInfo> _dicGetRepositoryDbField = new ConcurrentDictionary<Type, FieldInfo>();
|
||||
static FieldInfo GetRepositoryDbField(Type type) => _dicGetRepositoryDbField.GetOrAdd(type, tp => typeof(BaseRepository<,>).MakeGenericType(tp, typeof(int)).GetField("_dbPriv", BindingFlags.Instance | BindingFlags.NonPublic));
|
||||
public override IDbSet Set(Type entityType)
|
||||
{
|
||||
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
|
||||
|
||||
var tb = _orm.CodeFirst.GetTableByEntity(entityType);
|
||||
if (tb == null) return null;
|
||||
var tb = _orm.CodeFirst.GetTableByEntity(entityType);
|
||||
if (tb == null) return null;
|
||||
|
||||
object repos = _repos;
|
||||
if (entityType != _repos.EntityType) {
|
||||
repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(entityType, typeof(int)), _repos.Orm);
|
||||
(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
|
||||
GetRepositoryDbField(entityType).SetValue(repos, this);
|
||||
object repos = _repos;
|
||||
if (entityType != _repos.EntityType)
|
||||
{
|
||||
repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(entityType, typeof(int)), _repos.Orm);
|
||||
(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
|
||||
GetRepositoryDbField(entityType).SetValue(repos, this);
|
||||
|
||||
typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EntityType)
|
||||
.Invoke(null, new object[] { repos, _repos });
|
||||
}
|
||||
typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EntityType)
|
||||
.Invoke(null, new object[] { repos, _repos });
|
||||
}
|
||||
|
||||
var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(entityType), repos) as IDbSet;
|
||||
if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
|
||||
return sd;
|
||||
}
|
||||
var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(entityType), repos) as IDbSet;
|
||||
if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
|
||||
return sd;
|
||||
}
|
||||
|
||||
public static void SetRepositoryDataFilter<TEntity>(object repos, BaseRepository<TEntity> baseRepo) where TEntity : class {
|
||||
var filter = baseRepo.DataFilter as DataFilter<TEntity>;
|
||||
DataFilterUtil.SetRepositoryDataFilter(repos, fl => {
|
||||
foreach (var f in filter._filters)
|
||||
fl.Apply<TEntity>(f.Key, f.Value.Expression);
|
||||
});
|
||||
}
|
||||
public static void SetRepositoryDataFilter<TEntity>(object repos, BaseRepository<TEntity> baseRepo) where TEntity : class
|
||||
{
|
||||
var filter = baseRepo.DataFilter as DataFilter<TEntity>;
|
||||
DataFilterUtil.SetRepositoryDataFilter(repos, fl =>
|
||||
{
|
||||
foreach (var f in filter._filters)
|
||||
fl.Apply<TEntity>(f.Key, f.Value.Expression);
|
||||
});
|
||||
}
|
||||
|
||||
public override int SaveChanges() {
|
||||
ExecCommand();
|
||||
var ret = _affrows;
|
||||
_affrows = 0;
|
||||
return ret;
|
||||
}
|
||||
async public override Task<int> SaveChangesAsync() {
|
||||
await ExecCommandAsync();
|
||||
var ret = _affrows;
|
||||
_affrows = 0;
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
public override int SaveChanges()
|
||||
{
|
||||
ExecCommand();
|
||||
var ret = _affrows;
|
||||
_affrows = 0;
|
||||
return ret;
|
||||
}
|
||||
async public override Task<int> SaveChangesAsync()
|
||||
{
|
||||
await ExecCommandAsync();
|
||||
var ret = _affrows;
|
||||
_affrows = 0;
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,58 +3,67 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace FreeSql {
|
||||
internal class RepositoryDbSet<TEntity> : DbSet<TEntity> where TEntity : class {
|
||||
namespace FreeSql
|
||||
{
|
||||
internal class RepositoryDbSet<TEntity> : DbSet<TEntity> where TEntity : class
|
||||
{
|
||||
|
||||
protected BaseRepository<TEntity> _repos;
|
||||
public RepositoryDbSet(BaseRepository<TEntity> repos) {
|
||||
_ctx = repos._db;
|
||||
_fsql = repos.Orm;
|
||||
_uow = repos.UnitOfWork;
|
||||
_repos = repos;
|
||||
}
|
||||
protected BaseRepository<TEntity> _repos;
|
||||
public RepositoryDbSet(BaseRepository<TEntity> repos)
|
||||
{
|
||||
_ctx = repos._db;
|
||||
_fsql = repos.Orm;
|
||||
_uow = repos.UnitOfWork;
|
||||
_repos = repos;
|
||||
}
|
||||
|
||||
protected override ISelect<TEntity> OrmSelect(object dywhere) {
|
||||
var select = base.OrmSelect(dywhere);
|
||||
protected override ISelect<TEntity> OrmSelect(object dywhere)
|
||||
{
|
||||
var select = base.OrmSelect(dywhere);
|
||||
|
||||
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters) select.Where(filter.Value.Expression);
|
||||
return select.AsTable(_repos.AsTableSelectInternal);
|
||||
}
|
||||
internal ISelect<TEntity> OrmSelectInternal(object dywhere) => OrmSelect(dywhere);
|
||||
protected override IUpdate<TEntity> OrmUpdate(IEnumerable<TEntity> entitys) {
|
||||
var update = base.OrmUpdate(entitys);
|
||||
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters) {
|
||||
if (entitys != null)
|
||||
foreach (var entity in entitys)
|
||||
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
|
||||
throw new Exception($"FreeSql.Repository Update 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},更新的数据不符合 {_fsql.GetEntityString(_entityType, entity)}");
|
||||
update.Where(filter.Value.Expression);
|
||||
}
|
||||
return update.AsTable(_repos.AsTableInternal);
|
||||
}
|
||||
internal IUpdate<TEntity> OrmUpdateInternal(IEnumerable<TEntity> entitys) => OrmUpdate(entitys);
|
||||
protected override IDelete<TEntity> OrmDelete(object dywhere) {
|
||||
var delete = base.OrmDelete(dywhere);
|
||||
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters) delete.Where(filter.Value.Expression);
|
||||
return delete.AsTable(_repos.AsTableInternal);
|
||||
}
|
||||
internal IDelete<TEntity> OrmDeleteInternal(object dywhere) => OrmDelete(dywhere);
|
||||
protected override IInsert<TEntity> OrmInsert(TEntity entity) => OrmInsert(new[] { entity });
|
||||
protected override IInsert<TEntity> OrmInsert(IEnumerable<TEntity> entitys) {
|
||||
var insert = base.OrmInsert(entitys);
|
||||
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters) {
|
||||
if (entitys != null)
|
||||
foreach (var entity in entitys)
|
||||
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
|
||||
throw new Exception($"FreeSql.Repository Insert 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},插入的数据不符合 {_fsql.GetEntityString(_entityType, entity)}");
|
||||
}
|
||||
return insert.AsTable(_repos.AsTableInternal);
|
||||
}
|
||||
internal IInsert<TEntity> OrmInsertInternal(TEntity entity) => OrmInsert(entity);
|
||||
internal IInsert<TEntity> OrmInsertInternal(IEnumerable<TEntity> entitys) => OrmInsert(entitys);
|
||||
}
|
||||
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters) select.Where(filter.Value.Expression);
|
||||
return select.AsTable(_repos.AsTableSelectInternal);
|
||||
}
|
||||
internal ISelect<TEntity> OrmSelectInternal(object dywhere) => OrmSelect(dywhere);
|
||||
protected override IUpdate<TEntity> OrmUpdate(IEnumerable<TEntity> entitys)
|
||||
{
|
||||
var update = base.OrmUpdate(entitys);
|
||||
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters)
|
||||
{
|
||||
if (entitys != null)
|
||||
foreach (var entity in entitys)
|
||||
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
|
||||
throw new Exception($"FreeSql.Repository Update 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},更新的数据不符合 {_fsql.GetEntityString(_entityType, entity)}");
|
||||
update.Where(filter.Value.Expression);
|
||||
}
|
||||
return update.AsTable(_repos.AsTableInternal);
|
||||
}
|
||||
internal IUpdate<TEntity> OrmUpdateInternal(IEnumerable<TEntity> entitys) => OrmUpdate(entitys);
|
||||
protected override IDelete<TEntity> OrmDelete(object dywhere)
|
||||
{
|
||||
var delete = base.OrmDelete(dywhere);
|
||||
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters) delete.Where(filter.Value.Expression);
|
||||
return delete.AsTable(_repos.AsTableInternal);
|
||||
}
|
||||
internal IDelete<TEntity> OrmDeleteInternal(object dywhere) => OrmDelete(dywhere);
|
||||
protected override IInsert<TEntity> OrmInsert(TEntity entity) => OrmInsert(new[] { entity });
|
||||
protected override IInsert<TEntity> OrmInsert(IEnumerable<TEntity> entitys)
|
||||
{
|
||||
var insert = base.OrmInsert(entitys);
|
||||
var filters = (_repos.DataFilter as DataFilter<TEntity>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters)
|
||||
{
|
||||
if (entitys != null)
|
||||
foreach (var entity in entitys)
|
||||
if (filter.Value.ExpressionDelegate?.Invoke(entity) == false)
|
||||
throw new Exception($"FreeSql.Repository Insert 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},插入的数据不符合 {_fsql.GetEntityString(_entityType, entity)}");
|
||||
}
|
||||
return insert.AsTable(_repos.AsTableInternal);
|
||||
}
|
||||
internal IInsert<TEntity> OrmInsertInternal(TEntity entity) => OrmInsert(entity);
|
||||
internal IInsert<TEntity> OrmInsertInternal(IEnumerable<TEntity> entitys) => OrmInsert(entitys);
|
||||
}
|
||||
}
|
||||
|
@ -1,57 +1,64 @@
|
||||
using System;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace FreeSql {
|
||||
namespace FreeSql
|
||||
{
|
||||
|
||||
public interface IRepositoryUnitOfWork : IUnitOfWork {
|
||||
/// <summary>
|
||||
/// 在工作单元内创建默认仓库类,工作单元下的仓储操作具有事务特点
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <typeparam name="TKey"></typeparam>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <returns></returns>
|
||||
DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
|
||||
public interface IRepositoryUnitOfWork : IUnitOfWork
|
||||
{
|
||||
/// <summary>
|
||||
/// 在工作单元内创建默认仓库类,工作单元下的仓储操作具有事务特点
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <typeparam name="TKey"></typeparam>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <returns></returns>
|
||||
DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
|
||||
|
||||
/// <summary>
|
||||
/// 在工作单元内创建联合主键的仓储类,工作单元下的仓储操作具有事务特点
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <returns></returns>
|
||||
BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
|
||||
/// <summary>
|
||||
/// 在工作单元内创建联合主键的仓储类,工作单元下的仓储操作具有事务特点
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <returns></returns>
|
||||
BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class;
|
||||
|
||||
/// <summary>
|
||||
/// 在工作单元内创建仓库类,工作单元下的仓储操作具有事务特点
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param>
|
||||
/// <returns></returns>
|
||||
GuidRepository<TEntity> GetGuidRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class;
|
||||
}
|
||||
/// <summary>
|
||||
/// 在工作单元内创建仓库类,工作单元下的仓储操作具有事务特点
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param>
|
||||
/// <returns></returns>
|
||||
GuidRepository<TEntity> GetGuidRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class;
|
||||
}
|
||||
|
||||
class RepositoryUnitOfWork : UnitOfWork, IRepositoryUnitOfWork {
|
||||
class RepositoryUnitOfWork : UnitOfWork, IRepositoryUnitOfWork
|
||||
{
|
||||
|
||||
public RepositoryUnitOfWork(IFreeSql fsql) : base(fsql) {
|
||||
}
|
||||
public RepositoryUnitOfWork(IFreeSql fsql) : base(fsql)
|
||||
{
|
||||
}
|
||||
|
||||
public GuidRepository<TEntity> GetGuidRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class {
|
||||
var repos = new GuidRepository<TEntity>(_fsql, filter, asTable);
|
||||
repos.UnitOfWork = this;
|
||||
return repos;
|
||||
}
|
||||
public GuidRepository<TEntity> GetGuidRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class
|
||||
{
|
||||
var repos = new GuidRepository<TEntity>(_fsql, filter, asTable);
|
||||
repos.UnitOfWork = this;
|
||||
return repos;
|
||||
}
|
||||
|
||||
public DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class {
|
||||
var repos = new DefaultRepository<TEntity, TKey>(_fsql, filter);
|
||||
repos.UnitOfWork = this;
|
||||
return repos;
|
||||
}
|
||||
public DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class
|
||||
{
|
||||
var repos = new DefaultRepository<TEntity, TKey>(_fsql, filter);
|
||||
repos.UnitOfWork = this;
|
||||
return repos;
|
||||
}
|
||||
|
||||
public BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class {
|
||||
var repos = new DefaultRepository<TEntity, int>(_fsql, filter);
|
||||
repos.UnitOfWork = this;
|
||||
return repos;
|
||||
}
|
||||
}
|
||||
public BaseRepository<TEntity> GetRepository<TEntity>(Expression<Func<TEntity, bool>> filter = null) where TEntity : class
|
||||
{
|
||||
var repos = new DefaultRepository<TEntity, int>(_fsql, filter);
|
||||
repos.UnitOfWork = this;
|
||||
return repos;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -4,149 +4,178 @@ using System.Collections.Concurrent;
|
||||
using System.Linq.Expressions;
|
||||
using System.Linq;
|
||||
|
||||
namespace FreeSql {
|
||||
public interface IDataFilter<TEntity> : IDisposable where TEntity : class {
|
||||
namespace FreeSql
|
||||
{
|
||||
public interface IDataFilter<TEntity> : IDisposable where TEntity : class
|
||||
{
|
||||
|
||||
IDataFilter<TEntity> Apply(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp);
|
||||
IDataFilter<TEntity> Apply(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp);
|
||||
|
||||
/// <summary>
|
||||
/// 开启过滤器,若使用 using 则使用完后,恢复为原有状态
|
||||
/// </summary>
|
||||
/// <param name="filterName">过滤器名称</param>
|
||||
/// <returns></returns>
|
||||
IDisposable Enable(params string[] filterName);
|
||||
/// <summary>
|
||||
/// 开启所有过滤器,若使用 using 则使用完后,恢复为原有状态
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IDisposable EnableAll();
|
||||
/// <summary>
|
||||
/// 开启过滤器,若使用 using 则使用完后,恢复为原有状态
|
||||
/// </summary>
|
||||
/// <param name="filterName">过滤器名称</param>
|
||||
/// <returns></returns>
|
||||
IDisposable Enable(params string[] filterName);
|
||||
/// <summary>
|
||||
/// 开启所有过滤器,若使用 using 则使用完后,恢复为原有状态
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IDisposable EnableAll();
|
||||
|
||||
/// <summary>
|
||||
/// 禁用过滤器,若使用 using 则使用完后,恢复为原有状态
|
||||
/// </summary>
|
||||
/// <param name="filterName"></param>
|
||||
/// <returns></returns>
|
||||
IDisposable Disable(params string[] filterName);
|
||||
/// <summary>
|
||||
/// 禁用所有过滤器,若使用 using 则使用完后,恢复为原有状态
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IDisposable DisableAll();
|
||||
/// <summary>
|
||||
/// 禁用过滤器,若使用 using 则使用完后,恢复为原有状态
|
||||
/// </summary>
|
||||
/// <param name="filterName"></param>
|
||||
/// <returns></returns>
|
||||
IDisposable Disable(params string[] filterName);
|
||||
/// <summary>
|
||||
/// 禁用所有过滤器,若使用 using 则使用完后,恢复为原有状态
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IDisposable DisableAll();
|
||||
|
||||
bool IsEnabled(string filterName);
|
||||
}
|
||||
bool IsEnabled(string filterName);
|
||||
}
|
||||
|
||||
internal class DataFilter<TEntity> : IDataFilter<TEntity> where TEntity : class {
|
||||
internal class DataFilter<TEntity> : IDataFilter<TEntity> where TEntity : class
|
||||
{
|
||||
|
||||
internal class FilterItem {
|
||||
public Expression<Func<TEntity, bool>> Expression { get; set; }
|
||||
Func<TEntity, bool> _expressionDelegate;
|
||||
public Func<TEntity, bool> ExpressionDelegate => _expressionDelegate ?? (_expressionDelegate = Expression?.Compile());
|
||||
public bool IsEnabled { get; set; }
|
||||
}
|
||||
internal class FilterItem
|
||||
{
|
||||
public Expression<Func<TEntity, bool>> Expression { get; set; }
|
||||
Func<TEntity, bool> _expressionDelegate;
|
||||
public Func<TEntity, bool> ExpressionDelegate => _expressionDelegate ?? (_expressionDelegate = Expression?.Compile());
|
||||
public bool IsEnabled { get; set; }
|
||||
}
|
||||
|
||||
internal ConcurrentDictionary<string, FilterItem> _filters = new ConcurrentDictionary<string, FilterItem>(StringComparer.CurrentCultureIgnoreCase);
|
||||
public IDataFilter<TEntity> Apply(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp) {
|
||||
internal ConcurrentDictionary<string, FilterItem> _filters = new ConcurrentDictionary<string, FilterItem>(StringComparer.CurrentCultureIgnoreCase);
|
||||
public IDataFilter<TEntity> Apply(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp)
|
||||
{
|
||||
|
||||
if (filterName == null)
|
||||
throw new ArgumentNullException(nameof(filterName));
|
||||
if (filterAndValidateExp == null) return this;
|
||||
if (filterName == null)
|
||||
throw new ArgumentNullException(nameof(filterName));
|
||||
if (filterAndValidateExp == null) return this;
|
||||
|
||||
var filterItem = new FilterItem { Expression = filterAndValidateExp, IsEnabled = true };
|
||||
_filters.AddOrUpdate(filterName, filterItem, (k, v) => filterItem);
|
||||
return this;
|
||||
}
|
||||
var filterItem = new FilterItem { Expression = filterAndValidateExp, IsEnabled = true };
|
||||
_filters.AddOrUpdate(filterName, filterItem, (k, v) => filterItem);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IDisposable Disable(params string[] filterName) {
|
||||
if (filterName == null || filterName.Any() == false) return new UsingAny(() => { });
|
||||
public IDisposable Disable(params string[] filterName)
|
||||
{
|
||||
if (filterName == null || filterName.Any() == false) return new UsingAny(() => { });
|
||||
|
||||
List<string> restore = new List<string>();
|
||||
foreach (var name in filterName) {
|
||||
if (_filters.TryGetValue(name, out var tryfi)) {
|
||||
if (tryfi.IsEnabled) {
|
||||
restore.Add(name);
|
||||
tryfi.IsEnabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new UsingAny(() => this.Enable(restore.ToArray()));
|
||||
}
|
||||
public IDisposable DisableAll() {
|
||||
List<string> restore = new List<string>();
|
||||
foreach (var val in _filters) {
|
||||
if (val.Value.IsEnabled) {
|
||||
restore.Add(val.Key);
|
||||
val.Value.IsEnabled = false;
|
||||
}
|
||||
}
|
||||
return new UsingAny(() => this.Enable(restore.ToArray()));
|
||||
}
|
||||
class UsingAny : IDisposable {
|
||||
Action _ondis;
|
||||
public UsingAny(Action ondis) {
|
||||
_ondis = ondis;
|
||||
}
|
||||
public void Dispose() {
|
||||
_ondis?.Invoke();
|
||||
}
|
||||
}
|
||||
List<string> restore = new List<string>();
|
||||
foreach (var name in filterName)
|
||||
{
|
||||
if (_filters.TryGetValue(name, out var tryfi))
|
||||
{
|
||||
if (tryfi.IsEnabled)
|
||||
{
|
||||
restore.Add(name);
|
||||
tryfi.IsEnabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new UsingAny(() => this.Enable(restore.ToArray()));
|
||||
}
|
||||
public IDisposable DisableAll()
|
||||
{
|
||||
List<string> restore = new List<string>();
|
||||
foreach (var val in _filters)
|
||||
{
|
||||
if (val.Value.IsEnabled)
|
||||
{
|
||||
restore.Add(val.Key);
|
||||
val.Value.IsEnabled = false;
|
||||
}
|
||||
}
|
||||
return new UsingAny(() => this.Enable(restore.ToArray()));
|
||||
}
|
||||
class UsingAny : IDisposable
|
||||
{
|
||||
Action _ondis;
|
||||
public UsingAny(Action ondis)
|
||||
{
|
||||
_ondis = ondis;
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
_ondis?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public IDisposable Enable(params string[] filterName) {
|
||||
if (filterName == null || filterName.Any() == false) return new UsingAny(() => { });
|
||||
public IDisposable Enable(params string[] filterName)
|
||||
{
|
||||
if (filterName == null || filterName.Any() == false) return new UsingAny(() => { });
|
||||
|
||||
List<string> restore = new List<string>();
|
||||
foreach (var name in filterName) {
|
||||
if (_filters.TryGetValue(name, out var tryfi)) {
|
||||
if (tryfi.IsEnabled == false) {
|
||||
restore.Add(name);
|
||||
tryfi.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new UsingAny(() => this.Disable(restore.ToArray()));
|
||||
}
|
||||
public IDisposable EnableAll() {
|
||||
List<string> restore = new List<string>();
|
||||
foreach (var val in _filters) {
|
||||
if (val.Value.IsEnabled == false) {
|
||||
restore.Add(val.Key);
|
||||
val.Value.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
return new UsingAny(() => this.Disable(restore.ToArray()));
|
||||
}
|
||||
List<string> restore = new List<string>();
|
||||
foreach (var name in filterName)
|
||||
{
|
||||
if (_filters.TryGetValue(name, out var tryfi))
|
||||
{
|
||||
if (tryfi.IsEnabled == false)
|
||||
{
|
||||
restore.Add(name);
|
||||
tryfi.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new UsingAny(() => this.Disable(restore.ToArray()));
|
||||
}
|
||||
public IDisposable EnableAll()
|
||||
{
|
||||
List<string> restore = new List<string>();
|
||||
foreach (var val in _filters)
|
||||
{
|
||||
if (val.Value.IsEnabled == false)
|
||||
{
|
||||
restore.Add(val.Key);
|
||||
val.Value.IsEnabled = true;
|
||||
}
|
||||
}
|
||||
return new UsingAny(() => this.Disable(restore.ToArray()));
|
||||
}
|
||||
|
||||
public bool IsEnabled(string filterName) {
|
||||
if (filterName == null) return false;
|
||||
return _filters.TryGetValue(filterName, out var tryfi) ? tryfi.IsEnabled : false;
|
||||
}
|
||||
public bool IsEnabled(string filterName)
|
||||
{
|
||||
if (filterName == null) return false;
|
||||
return _filters.TryGetValue(filterName, out var tryfi) ? tryfi.IsEnabled : false;
|
||||
}
|
||||
|
||||
~DataFilter() {
|
||||
this.Dispose();
|
||||
}
|
||||
public void Dispose() {
|
||||
_filters.Clear();
|
||||
}
|
||||
}
|
||||
~DataFilter()
|
||||
{
|
||||
this.Dispose();
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
_filters.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
public class FluentDataFilter : IDisposable {
|
||||
public class FluentDataFilter : IDisposable
|
||||
{
|
||||
|
||||
internal List<(Type type, string name, LambdaExpression exp)> _filters = new List<(Type type, string name, LambdaExpression exp)>();
|
||||
internal List<(Type type, string name, LambdaExpression exp)> _filters = new List<(Type type, string name, LambdaExpression exp)>();
|
||||
|
||||
public FluentDataFilter Apply<TEntity>(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp) where TEntity : class {
|
||||
if (filterName == null)
|
||||
throw new ArgumentNullException(nameof(filterName));
|
||||
if (filterAndValidateExp == null) return this;
|
||||
public FluentDataFilter Apply<TEntity>(string filterName, Expression<Func<TEntity, bool>> filterAndValidateExp) where TEntity : class
|
||||
{
|
||||
if (filterName == null)
|
||||
throw new ArgumentNullException(nameof(filterName));
|
||||
if (filterAndValidateExp == null) return this;
|
||||
|
||||
_filters.Add((typeof(TEntity), filterName, filterAndValidateExp));
|
||||
return this;
|
||||
}
|
||||
_filters.Add((typeof(TEntity), filterName, filterAndValidateExp));
|
||||
return this;
|
||||
}
|
||||
|
||||
~FluentDataFilter() {
|
||||
this.Dispose();
|
||||
}
|
||||
public void Dispose() {
|
||||
_filters.Clear();
|
||||
}
|
||||
}
|
||||
~FluentDataFilter()
|
||||
{
|
||||
this.Dispose();
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
_filters.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,85 +5,100 @@ using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace FreeSql {
|
||||
namespace FreeSql
|
||||
{
|
||||
|
||||
internal class DataFilterUtil {
|
||||
internal class DataFilterUtil
|
||||
{
|
||||
|
||||
internal static Action<FluentDataFilter> _globalDataFilter;
|
||||
internal static Action<FluentDataFilter> _globalDataFilter;
|
||||
|
||||
static ConcurrentDictionary<Type, Delegate> _dicSetRepositoryDataFilterApplyDataFilterFunc = new ConcurrentDictionary<Type, Delegate>();
|
||||
static ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>> _dicSetRepositoryDataFilterConvertFilterNotExists = new ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>>();
|
||||
internal static void SetRepositoryDataFilter(object repos, Action<FluentDataFilter> scopedDataFilter) {
|
||||
if (scopedDataFilter != null) {
|
||||
SetRepositoryDataFilter(repos, null);
|
||||
}
|
||||
if (scopedDataFilter == null) {
|
||||
scopedDataFilter = _globalDataFilter;
|
||||
}
|
||||
if (scopedDataFilter == null) return;
|
||||
using (var globalFilter = new FluentDataFilter()) {
|
||||
scopedDataFilter(globalFilter);
|
||||
static ConcurrentDictionary<Type, Delegate> _dicSetRepositoryDataFilterApplyDataFilterFunc = new ConcurrentDictionary<Type, Delegate>();
|
||||
static ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>> _dicSetRepositoryDataFilterConvertFilterNotExists = new ConcurrentDictionary<Type, ConcurrentDictionary<string, bool>>();
|
||||
internal static void SetRepositoryDataFilter(object repos, Action<FluentDataFilter> scopedDataFilter)
|
||||
{
|
||||
if (scopedDataFilter != null)
|
||||
{
|
||||
SetRepositoryDataFilter(repos, null);
|
||||
}
|
||||
if (scopedDataFilter == null)
|
||||
{
|
||||
scopedDataFilter = _globalDataFilter;
|
||||
}
|
||||
if (scopedDataFilter == null) return;
|
||||
using (var globalFilter = new FluentDataFilter())
|
||||
{
|
||||
scopedDataFilter(globalFilter);
|
||||
|
||||
var type = repos.GetType();
|
||||
Type entityType = (repos as IBaseRepository).EntityType;
|
||||
if (entityType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository");
|
||||
var type = repos.GetType();
|
||||
Type entityType = (repos as IBaseRepository).EntityType;
|
||||
if (entityType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository");
|
||||
|
||||
var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary<string, bool>());
|
||||
var newFilter = new Dictionary<string, LambdaExpression>();
|
||||
foreach (var gf in globalFilter._filters) {
|
||||
if (notExists.ContainsKey(gf.name)) continue;
|
||||
var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary<string, bool>());
|
||||
var newFilter = new Dictionary<string, LambdaExpression>();
|
||||
foreach (var gf in globalFilter._filters)
|
||||
{
|
||||
if (notExists.ContainsKey(gf.name)) continue;
|
||||
|
||||
LambdaExpression newExp = null;
|
||||
var filterParameter1 = Expression.Parameter(entityType, gf.exp.Parameters[0].Name);
|
||||
try {
|
||||
newExp = Expression.Lambda(
|
||||
typeof(Func<,>).MakeGenericType(entityType, typeof(bool)),
|
||||
new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1),
|
||||
filterParameter1
|
||||
);
|
||||
} catch {
|
||||
notExists.TryAdd(gf.name, true); //防止第二次错误
|
||||
continue;
|
||||
}
|
||||
newFilter.Add(gf.name, newExp);
|
||||
}
|
||||
if (newFilter.Any() == false) return;
|
||||
LambdaExpression newExp = null;
|
||||
var filterParameter1 = Expression.Parameter(entityType, gf.exp.Parameters[0].Name);
|
||||
try
|
||||
{
|
||||
newExp = Expression.Lambda(
|
||||
typeof(Func<,>).MakeGenericType(entityType, typeof(bool)),
|
||||
new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1),
|
||||
filterParameter1
|
||||
);
|
||||
}
|
||||
catch
|
||||
{
|
||||
notExists.TryAdd(gf.name, true); //防止第二次错误
|
||||
continue;
|
||||
}
|
||||
newFilter.Add(gf.name, newExp);
|
||||
}
|
||||
if (newFilter.Any() == false) return;
|
||||
|
||||
var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t => {
|
||||
var reposParameter = Expression.Parameter(type);
|
||||
var nameParameter = Expression.Parameter(typeof(string));
|
||||
var expressionParameter = Expression.Parameter(
|
||||
typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(entityType, typeof(bool)))
|
||||
);
|
||||
return Expression.Lambda(
|
||||
Expression.Block(
|
||||
Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter)
|
||||
),
|
||||
new[] {
|
||||
reposParameter, nameParameter, expressionParameter
|
||||
}
|
||||
).Compile();
|
||||
});
|
||||
foreach (var nf in newFilter) {
|
||||
del.DynamicInvoke(repos, nf.Key, nf.Value);
|
||||
}
|
||||
newFilter.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t =>
|
||||
{
|
||||
var reposParameter = Expression.Parameter(type);
|
||||
var nameParameter = Expression.Parameter(typeof(string));
|
||||
var expressionParameter = Expression.Parameter(
|
||||
typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(entityType, typeof(bool)))
|
||||
);
|
||||
return Expression.Lambda(
|
||||
Expression.Block(
|
||||
Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter)
|
||||
),
|
||||
new[] {
|
||||
reposParameter, nameParameter, expressionParameter
|
||||
}
|
||||
).Compile();
|
||||
});
|
||||
foreach (var nf in newFilter)
|
||||
{
|
||||
del.DynamicInvoke(repos, nf.Key, nf.Value);
|
||||
}
|
||||
newFilter.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ReplaceVisitor : ExpressionVisitor {
|
||||
private ParameterExpression parameter;
|
||||
class ReplaceVisitor : ExpressionVisitor
|
||||
{
|
||||
private ParameterExpression parameter;
|
||||
|
||||
public Expression Modify(Expression expression, ParameterExpression parameter) {
|
||||
this.parameter = parameter;
|
||||
return Visit(expression);
|
||||
}
|
||||
public Expression Modify(Expression expression, ParameterExpression parameter)
|
||||
{
|
||||
this.parameter = parameter;
|
||||
return Visit(expression);
|
||||
}
|
||||
|
||||
protected override Expression VisitMember(MemberExpression node) {
|
||||
if (node.Expression?.NodeType == ExpressionType.Parameter)
|
||||
return Expression.Property(parameter, node.Member.Name);
|
||||
return base.VisitMember(node);
|
||||
}
|
||||
}
|
||||
protected override Expression VisitMember(MemberExpression node)
|
||||
{
|
||||
if (node.Expression?.NodeType == ExpressionType.Parameter)
|
||||
return Expression.Property(parameter, node.Member.Name);
|
||||
return base.VisitMember(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,35 +5,41 @@ using System.Reflection;
|
||||
using System.Linq;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace FreeSql {
|
||||
public static class FreeSqlRepositoryDependencyInjection {
|
||||
namespace FreeSql
|
||||
{
|
||||
public static class FreeSqlRepositoryDependencyInjection
|
||||
{
|
||||
|
||||
public static IServiceCollection AddFreeRepository(this IServiceCollection services, Action<FluentDataFilter> globalDataFilter = null, params Assembly[] assemblies) {
|
||||
public static IServiceCollection AddFreeRepository(this IServiceCollection services, Action<FluentDataFilter> globalDataFilter = null, params Assembly[] assemblies)
|
||||
{
|
||||
|
||||
DataFilterUtil._globalDataFilter = globalDataFilter;
|
||||
DataFilterUtil._globalDataFilter = globalDataFilter;
|
||||
|
||||
services.AddScoped(typeof(IReadOnlyRepository<>), typeof(GuidRepository<>));
|
||||
services.AddScoped(typeof(IBasicRepository<>), typeof(GuidRepository<>));
|
||||
services.AddScoped(typeof(BaseRepository<>), typeof(GuidRepository<>));
|
||||
services.AddScoped(typeof(GuidRepository<>));
|
||||
services.AddScoped(typeof(IReadOnlyRepository<>), typeof(GuidRepository<>));
|
||||
services.AddScoped(typeof(IBasicRepository<>), typeof(GuidRepository<>));
|
||||
services.AddScoped(typeof(BaseRepository<>), typeof(GuidRepository<>));
|
||||
services.AddScoped(typeof(GuidRepository<>));
|
||||
|
||||
services.AddScoped(typeof(IReadOnlyRepository<,>), typeof(DefaultRepository<,>));
|
||||
services.AddScoped(typeof(IBasicRepository<,>), typeof(DefaultRepository<,>));
|
||||
services.AddScoped(typeof(BaseRepository<,>), typeof(DefaultRepository<,>));
|
||||
services.AddScoped(typeof(DefaultRepository<,>));
|
||||
services.AddScoped(typeof(IReadOnlyRepository<,>), typeof(DefaultRepository<,>));
|
||||
services.AddScoped(typeof(IBasicRepository<,>), typeof(DefaultRepository<,>));
|
||||
services.AddScoped(typeof(BaseRepository<,>), typeof(DefaultRepository<,>));
|
||||
services.AddScoped(typeof(DefaultRepository<,>));
|
||||
|
||||
if (assemblies?.Any() == true) {
|
||||
foreach(var asse in assemblies) {
|
||||
foreach (var repos in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(IBaseRepository).IsAssignableFrom(a))) {
|
||||
if (assemblies?.Any() == true)
|
||||
{
|
||||
foreach (var asse in assemblies)
|
||||
{
|
||||
foreach (var repos in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(IBaseRepository).IsAssignableFrom(a)))
|
||||
{
|
||||
|
||||
services.AddScoped(repos);
|
||||
}
|
||||
}
|
||||
}
|
||||
services.AddScoped(repos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
@ -3,63 +3,69 @@ using System;
|
||||
using System.Linq.Expressions;
|
||||
using System.Linq;
|
||||
|
||||
public static class FreeSqlRepositoryExtenssions {
|
||||
public static class FreeSqlRepositoryExtenssions
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 返回默认仓库类
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <typeparam name="TKey"></typeparam>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <returns></returns>
|
||||
public static DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null) where TEntity : class {
|
||||
return new DefaultRepository<TEntity, TKey>(that, filter);
|
||||
}
|
||||
/// <summary>
|
||||
/// 返回默认仓库类
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <typeparam name="TKey"></typeparam>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <returns></returns>
|
||||
public static DefaultRepository<TEntity, TKey> GetRepository<TEntity, TKey>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null) where TEntity : class
|
||||
{
|
||||
return new DefaultRepository<TEntity, TKey>(that, filter);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回默认仓库类,适用联合主键的仓储类
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <returns></returns>
|
||||
public static BaseRepository<TEntity> GetRepository<TEntity>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null) where TEntity : class {
|
||||
return new DefaultRepository<TEntity, int>(that, filter);
|
||||
}
|
||||
/// <summary>
|
||||
/// 返回默认仓库类,适用联合主键的仓储类
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <returns></returns>
|
||||
public static BaseRepository<TEntity> GetRepository<TEntity>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null) where TEntity : class
|
||||
{
|
||||
return new DefaultRepository<TEntity, int>(that, filter);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回仓库类
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param>
|
||||
/// <returns></returns>
|
||||
public static GuidRepository<TEntity> GetGuidRepository<TEntity>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class {
|
||||
return new GuidRepository<TEntity>(that, filter, asTable);
|
||||
}
|
||||
/// <summary>
|
||||
/// 返回仓库类
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="filter">数据过滤 + 验证</param>
|
||||
/// <param name="asTable">分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository</param>
|
||||
/// <returns></returns>
|
||||
public static GuidRepository<TEntity> GetGuidRepository<TEntity>(this IFreeSql that, Expression<Func<TEntity, bool>> filter = null, Func<string, string> asTable = null) where TEntity : class
|
||||
{
|
||||
return new GuidRepository<TEntity>(that, filter, asTable);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合并两个仓储的设置(过滤+分表),以便查询
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <typeparam name="T2"></typeparam>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="repos"></param>
|
||||
/// <returns></returns>
|
||||
public static ISelect<TEntity> FromRepository<TEntity, T2>(this ISelect<TEntity> that, BaseRepository<T2> repos) where TEntity : class where T2 : class {
|
||||
var filters = (repos.DataFilter as DataFilter<T2>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters) that.Where<T2>(filter.Value.Expression);
|
||||
return that.AsTable(repos.AsTableSelectInternal);
|
||||
}
|
||||
/// <summary>
|
||||
/// 合并两个仓储的设置(过滤+分表),以便查询
|
||||
/// </summary>
|
||||
/// <typeparam name="TEntity"></typeparam>
|
||||
/// <typeparam name="T2"></typeparam>
|
||||
/// <param name="that"></param>
|
||||
/// <param name="repos"></param>
|
||||
/// <returns></returns>
|
||||
public static ISelect<TEntity> FromRepository<TEntity, T2>(this ISelect<TEntity> that, BaseRepository<T2> repos) where TEntity : class where T2 : class
|
||||
{
|
||||
var filters = (repos.DataFilter as DataFilter<T2>)._filters.Where(a => a.Value.IsEnabled == true);
|
||||
foreach (var filter in filters) that.Where<T2>(filter.Value.Expression);
|
||||
return that.AsTable(repos.AsTableSelectInternal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建基于仓储功能的工作单元,务必使用 using 包含使用
|
||||
/// </summary>
|
||||
/// <param name="that"></param>
|
||||
/// <returns></returns>
|
||||
public static IRepositoryUnitOfWork CreateUnitOfWork(this IFreeSql that) {
|
||||
return new RepositoryUnitOfWork(that);
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建基于仓储功能的工作单元,务必使用 using 包含使用
|
||||
/// </summary>
|
||||
/// <param name="that"></param>
|
||||
/// <returns></returns>
|
||||
public static IRepositoryUnitOfWork CreateUnitOfWork(this IFreeSql that)
|
||||
{
|
||||
return new RepositoryUnitOfWork(that);
|
||||
}
|
||||
}
|
@ -4,157 +4,185 @@ using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql {
|
||||
public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity>
|
||||
where TEntity : class {
|
||||
namespace FreeSql
|
||||
{
|
||||
public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity>
|
||||
where TEntity : class
|
||||
{
|
||||
|
||||
internal RepositoryDbContext _dbPriv;
|
||||
internal RepositoryDbContext _db => _dbPriv ?? (_dbPriv = new RepositoryDbContext(Orm, this));
|
||||
internal RepositoryDbSet<TEntity> _dbsetPriv;
|
||||
internal RepositoryDbSet<TEntity> _dbset => _dbsetPriv ?? (_dbsetPriv = _db.Set<TEntity>() as RepositoryDbSet<TEntity>);
|
||||
public IDataFilter<TEntity> DataFilter { get; } = new DataFilter<TEntity>();
|
||||
Func<string, string> _asTableVal;
|
||||
protected Func<string, string> AsTable {
|
||||
get => _asTableVal;
|
||||
set {
|
||||
_asTableVal = value;
|
||||
AsTableSelect = value == null ? null : new Func<Type, string, string>((a, b) => a == EntityType ? value(b) : null);
|
||||
}
|
||||
}
|
||||
internal Func<string, string> AsTableInternal => AsTable;
|
||||
protected Func<Type, string, string> AsTableSelect { get; private set; }
|
||||
internal Func<Type, string, string> AsTableSelectInternal => AsTableSelect;
|
||||
internal RepositoryDbContext _dbPriv;
|
||||
internal RepositoryDbContext _db => _dbPriv ?? (_dbPriv = new RepositoryDbContext(Orm, this));
|
||||
internal RepositoryDbSet<TEntity> _dbsetPriv;
|
||||
internal RepositoryDbSet<TEntity> _dbset => _dbsetPriv ?? (_dbsetPriv = _db.Set<TEntity>() as RepositoryDbSet<TEntity>);
|
||||
public IDataFilter<TEntity> DataFilter { get; } = new DataFilter<TEntity>();
|
||||
Func<string, string> _asTableVal;
|
||||
protected Func<string, string> AsTable
|
||||
{
|
||||
get => _asTableVal;
|
||||
set
|
||||
{
|
||||
_asTableVal = value;
|
||||
AsTableSelect = value == null ? null : new Func<Type, string, string>((a, b) => a == EntityType ? value(b) : null);
|
||||
}
|
||||
}
|
||||
internal Func<string, string> AsTableInternal => AsTable;
|
||||
protected Func<Type, string, string> AsTableSelect { get; private set; }
|
||||
internal Func<Type, string, string> AsTableSelectInternal => AsTableSelect;
|
||||
|
||||
protected void ApplyDataFilter(string name, Expression<Func<TEntity, bool>> exp) => DataFilter.Apply(name, exp);
|
||||
protected void ApplyDataFilter(string name, Expression<Func<TEntity, bool>> exp) => DataFilter.Apply(name, exp);
|
||||
|
||||
protected BaseRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable = null) {
|
||||
Orm = fsql;
|
||||
DataFilterUtil.SetRepositoryDataFilter(this, null);
|
||||
DataFilter.Apply("", filter);
|
||||
AsTable = asTable;
|
||||
}
|
||||
protected BaseRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable = null)
|
||||
{
|
||||
Orm = fsql;
|
||||
DataFilterUtil.SetRepositoryDataFilter(this, null);
|
||||
DataFilter.Apply("", filter);
|
||||
AsTable = asTable;
|
||||
}
|
||||
|
||||
~BaseRepository() {
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose() {
|
||||
if (_isdisposed) return;
|
||||
try {
|
||||
_dbsetPriv?.Dispose();
|
||||
_dbPriv?.Dispose();
|
||||
this.DataFilter.Dispose();
|
||||
} finally {
|
||||
_isdisposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
public Type EntityType => _dbsetPriv?.EntityType ?? typeof(TEntity);
|
||||
public void AsType(Type entityType) => _dbset.AsType(entityType);
|
||||
~BaseRepository()
|
||||
{
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose()
|
||||
{
|
||||
if (_isdisposed) return;
|
||||
try
|
||||
{
|
||||
_dbsetPriv?.Dispose();
|
||||
_dbPriv?.Dispose();
|
||||
this.DataFilter.Dispose();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isdisposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
public Type EntityType => _dbsetPriv?.EntityType ?? typeof(TEntity);
|
||||
public void AsType(Type entityType) => _dbset.AsType(entityType);
|
||||
|
||||
public IFreeSql Orm { get; private set; }
|
||||
public IUnitOfWork UnitOfWork { get; set; }
|
||||
public IUpdate<TEntity> UpdateDiy => _dbset.OrmUpdateInternal(null);
|
||||
public IFreeSql Orm { get; private set; }
|
||||
public IUnitOfWork UnitOfWork { get; set; }
|
||||
public IUpdate<TEntity> UpdateDiy => _dbset.OrmUpdateInternal(null);
|
||||
|
||||
public ISelect<TEntity> Select => _dbset.OrmSelectInternal(null);
|
||||
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => _dbset.OrmSelectInternal(null).Where(exp);
|
||||
public ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => _dbset.OrmSelectInternal(null).WhereIf(condition, exp);
|
||||
public ISelect<TEntity> Select => _dbset.OrmSelectInternal(null);
|
||||
public ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp) => _dbset.OrmSelectInternal(null).Where(exp);
|
||||
public ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp) => _dbset.OrmSelectInternal(null).WhereIf(condition, exp);
|
||||
|
||||
public int Delete(Expression<Func<TEntity, bool>> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrows();
|
||||
public Task<int> DeleteAsync(Expression<Func<TEntity, bool>> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrowsAsync();
|
||||
public int Delete(Expression<Func<TEntity, bool>> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrows();
|
||||
public Task<int> DeleteAsync(Expression<Func<TEntity, bool>> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrowsAsync();
|
||||
|
||||
public int Delete(TEntity entity) {
|
||||
_dbset.Remove(entity);
|
||||
return _db.SaveChanges();
|
||||
}
|
||||
public Task<int> DeleteAsync(TEntity entity) {
|
||||
_dbset.Remove(entity);
|
||||
return _db.SaveChangesAsync();
|
||||
}
|
||||
public int Delete(IEnumerable<TEntity> entitys) {
|
||||
_dbset.RemoveRange(entitys);
|
||||
return _db.SaveChanges();
|
||||
}
|
||||
public Task<int> DeleteAsync(IEnumerable<TEntity> entitys) {
|
||||
_dbset.RemoveRange(entitys);
|
||||
return _db.SaveChangesAsync();
|
||||
}
|
||||
public int Delete(TEntity entity)
|
||||
{
|
||||
_dbset.Remove(entity);
|
||||
return _db.SaveChanges();
|
||||
}
|
||||
public Task<int> DeleteAsync(TEntity entity)
|
||||
{
|
||||
_dbset.Remove(entity);
|
||||
return _db.SaveChangesAsync();
|
||||
}
|
||||
public int Delete(IEnumerable<TEntity> entitys)
|
||||
{
|
||||
_dbset.RemoveRange(entitys);
|
||||
return _db.SaveChanges();
|
||||
}
|
||||
public Task<int> DeleteAsync(IEnumerable<TEntity> entitys)
|
||||
{
|
||||
_dbset.RemoveRange(entitys);
|
||||
return _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public virtual TEntity Insert(TEntity entity) {
|
||||
_dbset.Add(entity);
|
||||
_db.SaveChanges();
|
||||
return entity;
|
||||
}
|
||||
async public virtual Task<TEntity> InsertAsync(TEntity entity) {
|
||||
await _dbset.AddAsync(entity);
|
||||
_db.SaveChanges();
|
||||
return entity;
|
||||
}
|
||||
public virtual List<TEntity> Insert(IEnumerable<TEntity> entitys) {
|
||||
_dbset.AddRange(entitys);
|
||||
_db.SaveChanges();
|
||||
return entitys.ToList();
|
||||
}
|
||||
async public virtual Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys) {
|
||||
await _dbset.AddRangeAsync(entitys);
|
||||
await _db.SaveChangesAsync();
|
||||
return entitys.ToList();
|
||||
}
|
||||
public virtual TEntity Insert(TEntity entity)
|
||||
{
|
||||
_dbset.Add(entity);
|
||||
_db.SaveChanges();
|
||||
return entity;
|
||||
}
|
||||
async public virtual Task<TEntity> InsertAsync(TEntity entity)
|
||||
{
|
||||
await _dbset.AddAsync(entity);
|
||||
_db.SaveChanges();
|
||||
return entity;
|
||||
}
|
||||
public virtual List<TEntity> Insert(IEnumerable<TEntity> entitys)
|
||||
{
|
||||
_dbset.AddRange(entitys);
|
||||
_db.SaveChanges();
|
||||
return entitys.ToList();
|
||||
}
|
||||
async public virtual Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys)
|
||||
{
|
||||
await _dbset.AddRangeAsync(entitys);
|
||||
await _db.SaveChangesAsync();
|
||||
return entitys.ToList();
|
||||
}
|
||||
|
||||
public int Update(TEntity entity) {
|
||||
_dbset.Update(entity);
|
||||
return _db.SaveChanges();
|
||||
}
|
||||
public Task<int> UpdateAsync(TEntity entity) {
|
||||
_dbset.Update(entity);
|
||||
return _db.SaveChangesAsync();
|
||||
}
|
||||
public int Update(IEnumerable<TEntity> entitys) {
|
||||
_dbset.UpdateRange(entitys);
|
||||
return _db.SaveChanges();
|
||||
}
|
||||
public Task<int> UpdateAsync(IEnumerable<TEntity> entitys) {
|
||||
_dbset.UpdateRange(entitys);
|
||||
return _db.SaveChangesAsync();
|
||||
}
|
||||
public int Update(TEntity entity)
|
||||
{
|
||||
_dbset.Update(entity);
|
||||
return _db.SaveChanges();
|
||||
}
|
||||
public Task<int> UpdateAsync(TEntity entity)
|
||||
{
|
||||
_dbset.Update(entity);
|
||||
return _db.SaveChangesAsync();
|
||||
}
|
||||
public int Update(IEnumerable<TEntity> entitys)
|
||||
{
|
||||
_dbset.UpdateRange(entitys);
|
||||
return _db.SaveChanges();
|
||||
}
|
||||
public Task<int> UpdateAsync(IEnumerable<TEntity> entitys)
|
||||
{
|
||||
_dbset.UpdateRange(entitys);
|
||||
return _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public void Attach(TEntity data) => _db.Attach(data);
|
||||
public void Attach(IEnumerable<TEntity> data) => _db.AttachRange(data);
|
||||
public void FlushState() => _dbset.FlushState();
|
||||
public void Attach(TEntity data) => _db.Attach(data);
|
||||
public void Attach(IEnumerable<TEntity> data) => _db.AttachRange(data);
|
||||
public void FlushState() => _dbset.FlushState();
|
||||
|
||||
public TEntity InsertOrUpdate(TEntity entity) {
|
||||
_dbset.AddOrUpdate(entity);
|
||||
_db.SaveChanges();
|
||||
return entity;
|
||||
}
|
||||
async public Task<TEntity> InsertOrUpdateAsync(TEntity entity) {
|
||||
await _dbset.AddOrUpdateAsync(entity);
|
||||
_db.SaveChanges();
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
public TEntity InsertOrUpdate(TEntity entity)
|
||||
{
|
||||
_dbset.AddOrUpdate(entity);
|
||||
_db.SaveChanges();
|
||||
return entity;
|
||||
}
|
||||
async public Task<TEntity> InsertOrUpdateAsync(TEntity entity)
|
||||
{
|
||||
await _dbset.AddOrUpdateAsync(entity);
|
||||
_db.SaveChanges();
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class BaseRepository<TEntity, TKey> : BaseRepository<TEntity>, IBaseRepository<TEntity, TKey>
|
||||
where TEntity : class {
|
||||
public abstract class BaseRepository<TEntity, TKey> : BaseRepository<TEntity>, IBaseRepository<TEntity, TKey>
|
||||
where TEntity : class
|
||||
{
|
||||
|
||||
public BaseRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable = null) : base(fsql, filter, asTable) {
|
||||
}
|
||||
public BaseRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable = null) : base(fsql, filter, asTable)
|
||||
{
|
||||
}
|
||||
|
||||
public int Delete(TKey id) {
|
||||
var stateKey = string.Concat(id);
|
||||
_dbset._statesInternal.TryRemove(stateKey, out var trystate);
|
||||
return _dbset.OrmDeleteInternal(id).ExecuteAffrows();
|
||||
}
|
||||
public Task<int> DeleteAsync(TKey id) {
|
||||
var stateKey = string.Concat(id);
|
||||
_dbset._statesInternal.TryRemove(stateKey, out var trystate);
|
||||
return _dbset.OrmDeleteInternal(id).ExecuteAffrowsAsync();
|
||||
}
|
||||
public int Delete(TKey id)
|
||||
{
|
||||
var stateKey = string.Concat(id);
|
||||
_dbset._statesInternal.TryRemove(stateKey, out var trystate);
|
||||
return _dbset.OrmDeleteInternal(id).ExecuteAffrows();
|
||||
}
|
||||
public Task<int> DeleteAsync(TKey id)
|
||||
{
|
||||
var stateKey = string.Concat(id);
|
||||
_dbset._statesInternal.TryRemove(stateKey, out var trystate);
|
||||
return _dbset.OrmDeleteInternal(id).ExecuteAffrowsAsync();
|
||||
}
|
||||
|
||||
public TEntity Find(TKey id) => _dbset.OrmSelectInternal(id).ToOne();
|
||||
public Task<TEntity> FindAsync(TKey id) => _dbset.OrmSelectInternal(id).ToOneAsync();
|
||||
public TEntity Find(TKey id) => _dbset.OrmSelectInternal(id).ToOne();
|
||||
public Task<TEntity> FindAsync(TKey id) => _dbset.OrmSelectInternal(id).ToOneAsync();
|
||||
|
||||
public TEntity Get(TKey id) => Find(id);
|
||||
public Task<TEntity> GetAsync(TKey id) => FindAsync(id);
|
||||
}
|
||||
public TEntity Get(TKey id) => Find(id);
|
||||
public Task<TEntity> GetAsync(TKey id) => FindAsync(id);
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +1,20 @@
|
||||
using System;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace FreeSql {
|
||||
public class DefaultRepository<TEntity, TKey> :
|
||||
BaseRepository<TEntity, TKey>
|
||||
where TEntity : class {
|
||||
namespace FreeSql
|
||||
{
|
||||
public class DefaultRepository<TEntity, TKey> :
|
||||
BaseRepository<TEntity, TKey>
|
||||
where TEntity : class
|
||||
{
|
||||
|
||||
public DefaultRepository(IFreeSql fsql) : base(fsql, null, null) {
|
||||
public DefaultRepository(IFreeSql fsql) : base(fsql, null, null)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public DefaultRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter) : base(fsql, filter, null) {
|
||||
}
|
||||
}
|
||||
public DefaultRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter) : base(fsql, filter, null)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,15 +1,19 @@
|
||||
using System;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace FreeSql {
|
||||
public class GuidRepository<TEntity> :
|
||||
BaseRepository<TEntity, Guid>
|
||||
where TEntity : class {
|
||||
namespace FreeSql
|
||||
{
|
||||
public class GuidRepository<TEntity> :
|
||||
BaseRepository<TEntity, Guid>
|
||||
where TEntity : class
|
||||
{
|
||||
|
||||
public GuidRepository(IFreeSql fsql) : this(fsql, null, null) {
|
||||
public GuidRepository(IFreeSql fsql) : this(fsql, null, null)
|
||||
{
|
||||
|
||||
}
|
||||
public GuidRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable) : base(fsql, filter, asTable) {
|
||||
}
|
||||
}
|
||||
}
|
||||
public GuidRepository(IFreeSql fsql, Expression<Func<TEntity, bool>> filter, Func<string, string> asTable) : base(fsql, filter, asTable)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,29 +2,33 @@
|
||||
using System.Linq.Expressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql {
|
||||
namespace FreeSql
|
||||
{
|
||||
|
||||
public interface IBaseRepository : IDisposable {
|
||||
Type EntityType { get; }
|
||||
IUnitOfWork UnitOfWork { get; set; }
|
||||
IFreeSql Orm { get; }
|
||||
public interface IBaseRepository : IDisposable
|
||||
{
|
||||
Type EntityType { get; }
|
||||
IUnitOfWork UnitOfWork { get; set; }
|
||||
IFreeSql Orm { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 动态Type,在使用 Repository<object> 后使用本方法,指定实体类型
|
||||
/// </summary>
|
||||
/// <param name="entityType"></param>
|
||||
/// <returns></returns>
|
||||
void AsType(Type entityType);
|
||||
}
|
||||
/// <summary>
|
||||
/// 动态Type,在使用 Repository<object> 后使用本方法,指定实体类型
|
||||
/// </summary>
|
||||
/// <param name="entityType"></param>
|
||||
/// <returns></returns>
|
||||
void AsType(Type entityType);
|
||||
}
|
||||
|
||||
public interface IBaseRepository<TEntity> : IReadOnlyRepository<TEntity>, IBasicRepository<TEntity>
|
||||
where TEntity : class {
|
||||
int Delete(Expression<Func<TEntity, bool>> predicate);
|
||||
public interface IBaseRepository<TEntity> : IReadOnlyRepository<TEntity>, IBasicRepository<TEntity>
|
||||
where TEntity : class
|
||||
{
|
||||
int Delete(Expression<Func<TEntity, bool>> predicate);
|
||||
|
||||
Task<int> DeleteAsync(Expression<Func<TEntity, bool>> predicate);
|
||||
}
|
||||
Task<int> DeleteAsync(Expression<Func<TEntity, bool>> predicate);
|
||||
}
|
||||
|
||||
public interface IBaseRepository<TEntity, TKey> : IBaseRepository<TEntity>, IReadOnlyRepository<TEntity, TKey>, IBasicRepository<TEntity, TKey>
|
||||
where TEntity : class {
|
||||
}
|
||||
public interface IBaseRepository<TEntity, TKey> : IBaseRepository<TEntity>, IReadOnlyRepository<TEntity, TKey>, IBasicRepository<TEntity, TKey>
|
||||
where TEntity : class
|
||||
{
|
||||
}
|
||||
}
|
@ -1,45 +1,48 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql {
|
||||
public interface IBasicRepository<TEntity> : IReadOnlyRepository<TEntity>
|
||||
where TEntity : class {
|
||||
TEntity Insert(TEntity entity);
|
||||
List<TEntity> Insert(IEnumerable<TEntity> entitys);
|
||||
Task<TEntity> InsertAsync(TEntity entity);
|
||||
Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys);
|
||||
namespace FreeSql
|
||||
{
|
||||
public interface IBasicRepository<TEntity> : IReadOnlyRepository<TEntity>
|
||||
where TEntity : class
|
||||
{
|
||||
TEntity Insert(TEntity entity);
|
||||
List<TEntity> Insert(IEnumerable<TEntity> entitys);
|
||||
Task<TEntity> InsertAsync(TEntity entity);
|
||||
Task<List<TEntity>> InsertAsync(IEnumerable<TEntity> entitys);
|
||||
|
||||
/// <summary>
|
||||
/// 清空状态数据
|
||||
/// </summary>
|
||||
void FlushState();
|
||||
/// <summary>
|
||||
/// 附加实体,可用于不查询就更新或删除
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
void Attach(TEntity entity);
|
||||
void Attach(IEnumerable<TEntity> entity);
|
||||
int Update(TEntity entity);
|
||||
int Update(IEnumerable<TEntity> entitys);
|
||||
Task<int> UpdateAsync(TEntity entity);
|
||||
Task<int> UpdateAsync(IEnumerable<TEntity> entitys);
|
||||
/// <summary>
|
||||
/// 清空状态数据
|
||||
/// </summary>
|
||||
void FlushState();
|
||||
/// <summary>
|
||||
/// 附加实体,可用于不查询就更新或删除
|
||||
/// </summary>
|
||||
/// <param name="entity"></param>
|
||||
void Attach(TEntity entity);
|
||||
void Attach(IEnumerable<TEntity> entity);
|
||||
int Update(TEntity entity);
|
||||
int Update(IEnumerable<TEntity> entitys);
|
||||
Task<int> UpdateAsync(TEntity entity);
|
||||
Task<int> UpdateAsync(IEnumerable<TEntity> entitys);
|
||||
|
||||
TEntity InsertOrUpdate(TEntity entity);
|
||||
Task<TEntity> InsertOrUpdateAsync(TEntity entity);
|
||||
TEntity InsertOrUpdate(TEntity entity);
|
||||
Task<TEntity> InsertOrUpdateAsync(TEntity entity);
|
||||
|
||||
IUpdate<TEntity> UpdateDiy { get; }
|
||||
IUpdate<TEntity> UpdateDiy { get; }
|
||||
|
||||
int Delete(TEntity entity);
|
||||
int Delete(IEnumerable<TEntity> entitys);
|
||||
Task<int> DeleteAsync(TEntity entity);
|
||||
Task<int> DeleteAsync(IEnumerable<TEntity> entitys);
|
||||
}
|
||||
int Delete(TEntity entity);
|
||||
int Delete(IEnumerable<TEntity> entitys);
|
||||
Task<int> DeleteAsync(TEntity entity);
|
||||
Task<int> DeleteAsync(IEnumerable<TEntity> entitys);
|
||||
}
|
||||
|
||||
public interface IBasicRepository<TEntity, TKey> : IBasicRepository<TEntity>, IReadOnlyRepository<TEntity, TKey>
|
||||
where TEntity : class {
|
||||
int Delete(TKey id);
|
||||
public interface IBasicRepository<TEntity, TKey> : IBasicRepository<TEntity>, IReadOnlyRepository<TEntity, TKey>
|
||||
where TEntity : class
|
||||
{
|
||||
int Delete(TKey id);
|
||||
|
||||
Task<int> DeleteAsync(TKey id);
|
||||
}
|
||||
Task<int> DeleteAsync(TKey id);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -2,26 +2,29 @@
|
||||
using System.Linq.Expressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FreeSql {
|
||||
public interface IReadOnlyRepository<TEntity> : IBaseRepository
|
||||
where TEntity : class {
|
||||
namespace FreeSql
|
||||
{
|
||||
public interface IReadOnlyRepository<TEntity> : IBaseRepository
|
||||
where TEntity : class
|
||||
{
|
||||
|
||||
IDataFilter<TEntity> DataFilter { get; }
|
||||
IDataFilter<TEntity> DataFilter { get; }
|
||||
|
||||
ISelect<TEntity> Select { get; }
|
||||
ISelect<TEntity> Select { get; }
|
||||
|
||||
ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp);
|
||||
ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp);
|
||||
}
|
||||
ISelect<TEntity> Where(Expression<Func<TEntity, bool>> exp);
|
||||
ISelect<TEntity> WhereIf(bool condition, Expression<Func<TEntity, bool>> exp);
|
||||
}
|
||||
|
||||
public interface IReadOnlyRepository<TEntity, TKey> : IReadOnlyRepository<TEntity>
|
||||
where TEntity : class {
|
||||
TEntity Get(TKey id);
|
||||
public interface IReadOnlyRepository<TEntity, TKey> : IReadOnlyRepository<TEntity>
|
||||
where TEntity : class
|
||||
{
|
||||
TEntity Get(TKey id);
|
||||
|
||||
Task<TEntity> GetAsync(TKey id);
|
||||
Task<TEntity> GetAsync(TKey id);
|
||||
|
||||
TEntity Find(TKey id);
|
||||
TEntity Find(TKey id);
|
||||
|
||||
Task<TEntity> FindAsync(TKey id);
|
||||
}
|
||||
Task<TEntity> FindAsync(TKey id);
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,7 @@
|
||||
|
||||
namespace FreeSql.Extensions.EntityUtil {
|
||||
public static class TempExtensions {
|
||||
}
|
||||
namespace FreeSql.Extensions.EntityUtil
|
||||
{
|
||||
public static class TempExtensions
|
||||
{
|
||||
}
|
||||
}
|
||||
|
@ -2,12 +2,14 @@
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
|
||||
namespace FreeSql {
|
||||
public interface IUnitOfWork : IDisposable {
|
||||
namespace FreeSql
|
||||
{
|
||||
public interface IUnitOfWork : IDisposable
|
||||
{
|
||||
|
||||
DbTransaction GetOrBeginTransaction(bool isCreate = true);
|
||||
DbTransaction GetOrBeginTransaction(bool isCreate = true);
|
||||
|
||||
IsolationLevel? IsolationLevel { get; set; }
|
||||
IsolationLevel? IsolationLevel { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用工作单元
|
||||
@ -16,7 +18,7 @@ namespace FreeSql {
|
||||
|
||||
void Commit();
|
||||
|
||||
void Rollback();
|
||||
void Rollback();
|
||||
|
||||
/// <summary>
|
||||
/// 禁用工作单元
|
||||
|
@ -3,22 +3,26 @@ using System;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
|
||||
namespace FreeSql {
|
||||
class UnitOfWork : IUnitOfWork {
|
||||
namespace FreeSql
|
||||
{
|
||||
class UnitOfWork : IUnitOfWork
|
||||
{
|
||||
|
||||
protected IFreeSql _fsql;
|
||||
protected Object<DbConnection> _conn;
|
||||
protected DbTransaction _tran;
|
||||
protected IFreeSql _fsql;
|
||||
protected Object<DbConnection> _conn;
|
||||
protected DbTransaction _tran;
|
||||
|
||||
public UnitOfWork(IFreeSql fsql) {
|
||||
_fsql = fsql;
|
||||
}
|
||||
public UnitOfWork(IFreeSql fsql)
|
||||
{
|
||||
_fsql = fsql;
|
||||
}
|
||||
|
||||
void ReturnObject() {
|
||||
_fsql.Ado.MasterPool.Return(_conn);
|
||||
_tran = null;
|
||||
_conn = null;
|
||||
}
|
||||
void ReturnObject()
|
||||
{
|
||||
_fsql.Ado.MasterPool.Return(_conn);
|
||||
_tran = null;
|
||||
_conn = null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
@ -49,55 +53,74 @@ namespace FreeSql {
|
||||
|
||||
public IsolationLevel? IsolationLevel { get; set; }
|
||||
|
||||
public DbTransaction GetOrBeginTransaction(bool isCreate = true) {
|
||||
public DbTransaction GetOrBeginTransaction(bool isCreate = true)
|
||||
{
|
||||
|
||||
if (_tran != null) return _tran;
|
||||
if (isCreate == false) return null;
|
||||
if (_tran != null) return _tran;
|
||||
if (isCreate == false) return null;
|
||||
if (!Enable) return null;
|
||||
if (_conn != null) _fsql.Ado.MasterPool.Return(_conn);
|
||||
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;
|
||||
}
|
||||
_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();
|
||||
}
|
||||
}
|
||||
}
|
||||
~UnitOfWork() {
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose() {
|
||||
if (_isdisposed) return;
|
||||
try {
|
||||
this.Rollback();
|
||||
} finally {
|
||||
_isdisposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
public void Commit()
|
||||
{
|
||||
if (_tran != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
_tran.Commit();
|
||||
}
|
||||
finally
|
||||
{
|
||||
ReturnObject();
|
||||
}
|
||||
}
|
||||
}
|
||||
public void Rollback()
|
||||
{
|
||||
if (_tran != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
_tran.Rollback();
|
||||
}
|
||||
finally
|
||||
{
|
||||
ReturnObject();
|
||||
}
|
||||
}
|
||||
}
|
||||
~UnitOfWork()
|
||||
{
|
||||
this.Dispose();
|
||||
}
|
||||
bool _isdisposed = false;
|
||||
public void Dispose()
|
||||
{
|
||||
if (_isdisposed) return;
|
||||
try
|
||||
{
|
||||
this.Rollback();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isdisposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user