/// <summary> /// 返回模型对应的主键字段名 /// </summary> /// <returns>返回模型的主键列信息</returns> internal static Expression <Func <T, bool> > GetKeysExpression <T>(T entity) { var keyMeta = MapperConfig.GetKeyMetas <T>(); if (keyMeta == null) { throw Error.Exception("没有为模型" + typeof(T).FullName + "指定主键。"); } LambdaExpression body = null; ParameterExpression parameter = null; for (var i = 0; i < keyMeta.Length; i++) { var meta = keyMeta[i]; if (meta.Expression is LambdaExpression exp) { parameter = exp.Parameters.FirstOrDefault(); var key = exp.Compile().DynamicInvoke(entity); var keyExp = Expression.Constant(key); //var keyExp = Expression.MakeMemberAccess(constvar, meta.Member); var mem = exp.Body.ChangeType(keyExp.Type); var condition = Expression.Equal(keyExp, mem); var innerLambda = Expression.Lambda(condition, parameter); body = body.AndAlso(innerLambda); } } if (body != null) { return(Expression.Lambda <Func <T, bool> >(body.Body, parameter)); } return(null); }
/// <summary> /// 返回模型对应的主键字段名 /// </summary> /// <returns>返回模型的主键列信息</returns> internal static Expression <Func <T, bool> > GetKeysExpression <T>(params object[] keys) { var keyMeta = MapperConfig.GetKeyMetas <T>(); if (keyMeta == null) { throw Error.Exception("没有为模型" + typeof(T).FullName + "指定主键。"); } if (keys.Length != keyMeta.Length) { return(null); //throw Error.Exception("主键的列数目和给定的键值数目不相等。"); } LambdaExpression body = null; ParameterExpression parameter = null; for (var i = 0; i < keyMeta.Length; i++) { var meta = keyMeta[i]; if (meta.Expression is LambdaExpression exp) { parameter = exp.Parameters.FirstOrDefault(); var keyExp = Expression.Constant(keys[i]); var mem = exp.Body.ChangeType(keyExp.Type); var condition = Expression.Equal(keyExp, mem); var innerLambda = Expression.Lambda(condition, parameter); body = body.AndAlso(innerLambda); } } if (body != null) { return(Expression.Lambda <Func <T, bool> >(body.Body, parameter)); } return(null); }