- 增加 DateTime 扩展方法 Between 和 BetweenEnd 自定义表达式;

- 修复 Dto 映射,在二级即 Dto 属性上又 new Dto 的时候,错误的又重复映射了全部字段;
This commit is contained in:
28810 2019-12-06 18:18:38 +08:00
parent dbdcec3a6f
commit e59608a6c8
6 changed files with 66 additions and 27 deletions

View File

@ -110,13 +110,6 @@
清空状态数据 清空状态数据
</summary> </summary>
</member> </member>
<member name="M:FreeSql.DbSet`1.RemoveAsync(System.Linq.Expressions.Expression{System.Func{`0,System.Boolean}})">
<summary>
根据 lambda 条件删除数据
</summary>
<param name="predicate"></param>
<returns></returns>
</member>
<member name="M:FreeSql.DbSet`1.Add(`0)"> <member name="M:FreeSql.DbSet`1.Add(`0)">
<summary> <summary>
添加 添加

View File

@ -219,6 +219,12 @@ namespace FreeSql.Tests
[Fact] [Fact]
public void Test02() public void Test02()
{ {
var start = DateTime.Now.Date;
var end = DateTime.Now.AddDays(1).Date.AddMilliseconds(-1);
var textbetween = g.sqlite.Select<TestIgnoreDefaultValue>()
.Where(a => a.ct1.Between(start, end))
.ToList();
g.mysql.GlobalFilter.Apply<gf_t1>("gft1", a => a.rowstate > -1) g.mysql.GlobalFilter.Apply<gf_t1>("gft1", a => a.rowstate > -1)
.Apply<gf_t2>("gft2", a => a.rowstate > -2) .Apply<gf_t2>("gft2", a => a.rowstate > -2)
.Apply<gf_t3>("gft3", a => a.rowstate > -3); .Apply<gf_t3>("gft3", a => a.rowstate > -3);

View File

@ -1,4 +1,5 @@
using FreeSql; using FreeSql;
using FreeSql.DataAnnotations;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Concurrent; using System.Collections.Concurrent;
@ -9,6 +10,7 @@ using System.Drawing;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection; using System.Reflection;
using System.Threading;
public static partial class FreeSqlGlobalExtensions public static partial class FreeSqlGlobalExtensions
{ {
@ -102,10 +104,7 @@ public static partial class FreeSqlGlobalExtensions
var desc = item.GetType().GetField(name)?.GetCustomAttributes(typeof(DescriptionAttribute), false)?.FirstOrDefault() as DescriptionAttribute; var desc = item.GetType().GetField(name)?.GetCustomAttributes(typeof(DescriptionAttribute), false)?.FirstOrDefault() as DescriptionAttribute;
return desc?.Description ?? name; return desc?.Description ?? name;
} }
public static long ToInt64(this Enum item) public static long ToInt64(this Enum item) => Convert.ToInt64(item);
{
return Convert.ToInt64(item);
}
public static IEnumerable<T> ToSet<T>(this long value) public static IEnumerable<T> ToSet<T>(this long value)
{ {
var ret = new List<T>(); var ret = new List<T>();
@ -222,4 +221,45 @@ public static partial class FreeSqlGlobalExtensions
} }
#endif #endif
#endregion #endregion
#region LambdaExpression
public static ThreadLocal<ExpressionCallContext> expContext = new ThreadLocal<ExpressionCallContext>();
/// <summary>
/// C# that >= between &amp;&amp; that &lt;= and<para></para>
/// SQL that BETWEEN between AND and
/// </summary>
/// <param name="that"></param>
/// <param name="between"></param>
/// <param name="and"></param>
/// <returns></returns>
[ExpressionCall]
public static bool Between(this DateTime that, DateTime between, DateTime and)
{
if (expContext.IsValueCreated == false || expContext.Value == null || expContext.Value.ParsedContent == null)
return that >= between && that <= and;
expContext.Value.Result = $"{expContext.Value.ParsedContent["that"]} between {expContext.Value.ParsedContent["start"]} and {expContext.Value.ParsedContent["end"]}";
return false;
}
/// <summary>
/// 注意:这个方法和 Between 有细微区别<para></para>
/// C# that >= start &amp;&amp; that &lt; end<para></para>
/// SQL that >= start and that &lt; end
/// </summary>
/// <param name="that"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
[ExpressionCall]
public static bool BetweenEnd(this DateTime that, DateTime start, DateTime end)
{
if (expContext.IsValueCreated == false || expContext.Value == null || expContext.Value.ParsedContent == null)
return that >= start && that < end;
expContext.Value.Result = $"{expContext.Value.ParsedContent["that"]} >= {expContext.Value.ParsedContent["start"]} and {expContext.Value.ParsedContent["that"]} < {expContext.Value.ParsedContent["end"]}";
return false;
}
#endregion
} }

View File

@ -25,20 +25,20 @@ namespace FreeSql.Internal
_common = common; _common = common;
} }
public bool ReadAnonymousField(List<SelectTableInfo> _tables, StringBuilder field, ReadAnonymousTypeInfo parent, ref int index, Expression exp, Func<Expression[], string> getSelectGroupingMapString, List<LambdaExpression> whereCascadeExpression) public bool ReadAnonymousField(List<SelectTableInfo> _tables, StringBuilder field, ReadAnonymousTypeInfo parent, ref int index, Expression exp, Func<Expression[], string> getSelectGroupingMapString, List<LambdaExpression> whereCascadeExpression, bool isAllDtoMap)
{ {
Func<ExpTSC> getTSC = () => new ExpTSC { _tables = _tables, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where, whereCascadeExpression = whereCascadeExpression }; Func<ExpTSC> getTSC = () => new ExpTSC { _tables = _tables, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where, whereCascadeExpression = whereCascadeExpression };
switch (exp.NodeType) switch (exp.NodeType)
{ {
case ExpressionType.Quote: return ReadAnonymousField(_tables, field, parent, ref index, (exp as UnaryExpression)?.Operand, getSelectGroupingMapString, whereCascadeExpression); case ExpressionType.Quote: return ReadAnonymousField(_tables, field, parent, ref index, (exp as UnaryExpression)?.Operand, getSelectGroupingMapString, whereCascadeExpression, isAllDtoMap);
case ExpressionType.Lambda: return ReadAnonymousField(_tables, field, parent, ref index, (exp as LambdaExpression)?.Body, getSelectGroupingMapString, whereCascadeExpression); case ExpressionType.Lambda: return ReadAnonymousField(_tables, field, parent, ref index, (exp as LambdaExpression)?.Body, getSelectGroupingMapString, whereCascadeExpression, isAllDtoMap);
case ExpressionType.Negate: case ExpressionType.Negate:
case ExpressionType.NegateChecked: case ExpressionType.NegateChecked:
parent.DbField = $"-({ExpressionLambdaToSql(exp, getTSC())})"; parent.DbField = $"-({ExpressionLambdaToSql(exp, getTSC())})";
field.Append(", ").Append(parent.DbField); field.Append(", ").Append(parent.DbField);
if (index >= 0) field.Append(" as").Append(++index); if (index >= 0) field.Append(" as").Append(++index);
return false; return false;
case ExpressionType.Convert: return ReadAnonymousField(_tables, field, parent, ref index, (exp as UnaryExpression)?.Operand, getSelectGroupingMapString, whereCascadeExpression); case ExpressionType.Convert: return ReadAnonymousField(_tables, field, parent, ref index, (exp as UnaryExpression)?.Operand, getSelectGroupingMapString, whereCascadeExpression, isAllDtoMap);
case ExpressionType.Constant: case ExpressionType.Constant:
var constExp = exp as ConstantExpression; var constExp = exp as ConstantExpression;
//处理自定义SQL语句 ToList(new { //处理自定义SQL语句 ToList(new {
@ -110,7 +110,7 @@ namespace FreeSql.Internal
parent.Consturctor = initExp.NewExpression.Type.GetConstructors()[0]; parent.Consturctor = initExp.NewExpression.Type.GetConstructors()[0];
parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties;
if (_tables != null && _tables.Any() && initExp.NewExpression.Type != _tables.FirstOrDefault().Table.Type) if (isAllDtoMap && _tables != null && _tables.Any() && initExp.NewExpression.Type != _tables.FirstOrDefault().Table.Type)
{ {
//dto 映射 //dto 映射
var dtoProps = initExp.NewExpression.Type.GetPropertiesDictIgnoreCase().Values; var dtoProps = initExp.NewExpression.Type.GetPropertiesDictIgnoreCase().Values;
@ -129,7 +129,7 @@ namespace FreeSql.Internal
}; };
parent.Childs.Add(child); parent.Childs.Add(child);
if (dtTb.Parameter != null) if (dtTb.Parameter != null)
ReadAnonymousField(_tables, field, child, ref index, Expression.Property(dtTb.Parameter, dtTb.Table.Properties[trydtocol.CsName]), getSelectGroupingMapString, whereCascadeExpression); ReadAnonymousField(_tables, field, child, ref index, Expression.Property(dtTb.Parameter, dtTb.Table.Properties[trydtocol.CsName]), getSelectGroupingMapString, whereCascadeExpression, isAllDtoMap);
else else
{ {
child.DbField = $"{dtTb.Alias}.{_common.QuoteSqlName(trydtocol.Attribute.Name)}"; child.DbField = $"{dtTb.Alias}.{_common.QuoteSqlName(trydtocol.Attribute.Name)}";
@ -156,7 +156,7 @@ namespace FreeSql.Internal
MapType = initAssignExp.Expression.Type MapType = initAssignExp.Expression.Type
}; };
parent.Childs.Add(child); parent.Childs.Add(child);
ReadAnonymousField(_tables, field, child, ref index, initAssignExp.Expression, getSelectGroupingMapString, whereCascadeExpression); ReadAnonymousField(_tables, field, child, ref index, initAssignExp.Expression, getSelectGroupingMapString, whereCascadeExpression, false);
} }
} }
if (parent.Childs.Any() == false) throw new Exception($"映射异常:{initExp.NewExpression.Type.Name} 没有一个属性名相同"); if (parent.Childs.Any() == false) throw new Exception($"映射异常:{initExp.NewExpression.Type.Name} 没有一个属性名相同");
@ -177,7 +177,7 @@ namespace FreeSql.Internal
MapType = newExp.Arguments[a].Type MapType = newExp.Arguments[a].Type
}; };
parent.Childs.Add(child); parent.Childs.Add(child);
ReadAnonymousField(_tables, field, child, ref index, newExp.Arguments[a], getSelectGroupingMapString, whereCascadeExpression); ReadAnonymousField(_tables, field, child, ref index, newExp.Arguments[a], getSelectGroupingMapString, whereCascadeExpression, false);
} }
} }
else else
@ -200,7 +200,7 @@ namespace FreeSql.Internal
}; };
parent.Childs.Add(child); parent.Childs.Add(child);
if (dtTb.Parameter != null) if (dtTb.Parameter != null)
ReadAnonymousField(_tables, field, child, ref index, Expression.Property(dtTb.Parameter, dtTb.Table.Properties[trydtocol.CsName]), getSelectGroupingMapString, whereCascadeExpression); ReadAnonymousField(_tables, field, child, ref index, Expression.Property(dtTb.Parameter, dtTb.Table.Properties[trydtocol.CsName]), getSelectGroupingMapString, whereCascadeExpression, isAllDtoMap);
else else
{ {
child.DbField = $"{dtTb.Alias}.{_common.QuoteSqlName(trydtocol.Attribute.Name)}"; child.DbField = $"{dtTb.Alias}.{_common.QuoteSqlName(trydtocol.Attribute.Name)}";

View File

@ -530,7 +530,7 @@ namespace FreeSql.Internal.CommonProvider
var field = new StringBuilder(); var field = new StringBuilder();
var index = 0; var index = 0;
_commonExpression.ReadAnonymousField(_tables, field, map, ref index, newexp, null, _whereCascadeExpression); _commonExpression.ReadAnonymousField(_tables, field, map, ref index, newexp, null, _whereCascadeExpression, true);
return (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null); return (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null);
} }
static ConcurrentDictionary<Type, ConstructorInfo> _dicConstructor = new ConcurrentDictionary<Type, ConstructorInfo>(); static ConcurrentDictionary<Type, ConstructorInfo> _dicConstructor = new ConcurrentDictionary<Type, ConstructorInfo>();
@ -1003,7 +1003,7 @@ namespace FreeSql.Internal.CommonProvider
var field = new StringBuilder(); var field = new StringBuilder();
var index = -10000; //临时规则,不返回 as1 var index = -10000; //临时规则,不返回 as1
_commonExpression.ReadAnonymousField(_tables, field, map, ref index, columns, null, _whereCascadeExpression); _commonExpression.ReadAnonymousField(_tables, field, map, ref index, columns, null, _whereCascadeExpression, true);
this.GroupBy(field.Length > 0 ? field.Remove(0, 2).ToString() : null); this.GroupBy(field.Length > 0 ? field.Remove(0, 2).ToString() : null);
return new SelectGroupingProvider<TKey, TValue>(this, map, _commonExpression, _tables); return new SelectGroupingProvider<TKey, TValue>(this, map, _commonExpression, _tables);
} }
@ -1061,7 +1061,7 @@ namespace FreeSql.Internal.CommonProvider
var field = new StringBuilder(); var field = new StringBuilder();
var index = 0; var index = 0;
_commonExpression.ReadAnonymousField(_tables, field, map, ref index, select, null, _whereCascadeExpression); _commonExpression.ReadAnonymousField(_tables, field, map, ref index, select, null, _whereCascadeExpression, true);
return this.ToListMapReader<TReturn>((map, field.Length > 0 ? field.Remove(0, 2).ToString() : null)).FirstOrDefault(); return this.ToListMapReader<TReturn>((map, field.Length > 0 ? field.Remove(0, 2).ToString() : null)).FirstOrDefault();
} }
@ -1291,7 +1291,7 @@ namespace FreeSql.Internal.CommonProvider
var field = new StringBuilder(); var field = new StringBuilder();
var index = 0; var index = 0;
_commonExpression.ReadAnonymousField(_tables, field, map, ref index, select, null, _whereCascadeExpression); _commonExpression.ReadAnonymousField(_tables, field, map, ref index, select, null, _whereCascadeExpression, true);
return (await this.ToListMapReaderAsync<TReturn>((map, field.Length > 0 ? field.Remove(0, 2).ToString() : null))).FirstOrDefault(); return (await this.ToListMapReaderAsync<TReturn>((map, field.Length > 0 ? field.Remove(0, 2).ToString() : null))).FirstOrDefault();
} }
#endif #endif

View File

@ -112,7 +112,7 @@ namespace FreeSql.Internal.CommonProvider
var field = new StringBuilder(); var field = new StringBuilder();
var index = 0; var index = 0;
_comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString, null); _comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString, null, true);
var method = _select.GetType().GetMethod("ToListMapReader", BindingFlags.Instance | BindingFlags.NonPublic); var method = _select.GetType().GetMethod("ToListMapReader", BindingFlags.Instance | BindingFlags.NonPublic);
method = method.MakeGenericMethod(typeof(TReturn)); method = method.MakeGenericMethod(typeof(TReturn));
return method.Invoke(_select, new object[] { (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null) }) as List<TReturn>; return method.Invoke(_select, new object[] { (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null) }) as List<TReturn>;
@ -126,7 +126,7 @@ namespace FreeSql.Internal.CommonProvider
var field = new StringBuilder(); var field = new StringBuilder();
var index = 0; var index = 0;
_comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString, null); _comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString, null, true);
var method = _select.GetType().GetMethod("ToSql", new[] { typeof(string) }); var method = _select.GetType().GetMethod("ToSql", new[] { typeof(string) });
return method.Invoke(_select, new object[] { field.Length > 0 ? field.Remove(0, 2).ToString() : null }) as string; return method.Invoke(_select, new object[] { field.Length > 0 ? field.Remove(0, 2).ToString() : null }) as string;
} }
@ -170,7 +170,7 @@ namespace FreeSql.Internal.CommonProvider
var field = new StringBuilder(); var field = new StringBuilder();
var index = 0; var index = 0;
_comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString, null); _comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString, null, true);
var method = _select.GetType().GetMethod("ToListMapReaderAsync", BindingFlags.Instance | BindingFlags.NonPublic); var method = _select.GetType().GetMethod("ToListMapReaderAsync", BindingFlags.Instance | BindingFlags.NonPublic);
method = method.MakeGenericMethod(typeof(TReturn)); method = method.MakeGenericMethod(typeof(TReturn));
return method.Invoke(_select, new object[] { (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null) }) as Task<List<TReturn>>; return method.Invoke(_select, new object[] { (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null) }) as Task<List<TReturn>>;