예제 #1
0
        public static List <T> PageList <T>(this SqlConnection conn, ConditionBuilder condition, SortBuilder sort,
                                            int pageIndex, int pageSize, out int totalCount, SqlTransaction trans = null)
        {
            condition = condition ?? ConditionBuilder.New();
            sort      = sort ?? new SortBuilder();

            var info = EntityInfoContainer.Get(typeof(T));

            if (info.IsSoftDelete)
            {
                condition = condition.AndEqual("IsDel", false);
            }

            var sql = SqlServerSqlBuilder.PagingSelectWithTotalCount(info, condition.ToCondition(), sort.ToOrderBy(),
                                                                     pageIndex, pageSize);

            var parameters = condition.ToParameters();

            parameters.Add("RecordCount", dbType: DbType.Int32, direction: ParameterDirection.Output);

            var data = conn.Query <T>(sql, parameters, trans);

            totalCount = parameters.Get <int>("RecordCount");
            return(data.ToList());
        }
예제 #2
0
        private static MethodBuilder BuildEqualsMethod(
            string typeName,
            IReadOnlyList <PropertyDescriptor> properties)
        {
            const string other = nameof(other);

            ConditionBuilder equalCondition =
                ConditionBuilder
                .New()
                .SetReturn()
                .SetDetermineStatement();

            if (properties.Count == 0)
            {
                equalCondition.And("true");
            }
            else
            {
                foreach (PropertyDescriptor property in properties)
                {
                    equalCondition.And(ConditionBuilder
                                       .New()
                                       .Set(BuildPropertyComparison(property.Type, property.Name)));
                }
            }

            return(MethodBuilder
                   .New()
                   .SetName(nameof(IEquatable <object> .Equals))
                   .SetPublic()
                   .SetInheritance(Inheritance.Virtual)
                   .SetReturnType(TypeNames.Boolean)
                   .AddParameter(other, x => x.SetType(typeName.MakeNullable()))
                   .AddCode(CodeBlockBuilder
                            .New()
                            .AddCode(IfBuilder
                                     .New()
                                     .SetCondition(MethodCallBuilder
                                                   .Inline()
                                                   .SetMethodName(nameof(ReferenceEquals))
                                                   .AddArgument("null")
                                                   .AddArgument(other))
                                     .AddCode("return false;"))
                            .AddEmptyLine()
                            .AddCode(IfBuilder
                                     .New()
                                     .SetCondition(MethodCallBuilder
                                                   .Inline()
                                                   .SetMethodName(nameof(ReferenceEquals))
                                                   .AddArgument("this")
                                                   .AddArgument(other))
                                     .AddCode("return true;"))
                            .AddEmptyLine()
                            .AddCode(IfBuilder
                                     .New()
                                     .SetCondition($"{other}.GetType() != GetType()")
                                     .AddCode("return false;"))
                            .AddEmptyLine()
                            .AddCode(equalCondition)));
        }
예제 #3
0
        /// <summary>
        /// 修改指定条件数据的指定字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TPrimaryKey"></typeparam>
        /// <param name="conn"></param>
        /// <param name="fieldValueList">
        ///     要修改的字段和值对,注意这里的Field是数据表的字段,而不是实体的属性
        ///     FieldValuePairs.New().Add(字段, 值).Add(...)
        ///     注意:此方法不会忽略已指定为UpdateIgnore的字段
        /// </param>
        /// <param name="condition"></param>
        /// <param name="getUserKeyFunc"></param>
        /// <param name="trans"></param>
        /// <returns></returns>
        public static int Set <T, TPrimaryKey>(this SqlConnection conn,
                                               FieldValuePairs fieldValueList,
                                               ConditionBuilder condition,
                                               Func <TPrimaryKey> getUserKeyFunc = null,
                                               SqlTransaction trans = null) where T : IBaseEntity <TPrimaryKey>
        {
            condition      = condition ?? ConditionBuilder.New();
            fieldValueList = fieldValueList ?? FieldValuePairs.New();

            var info = EntityInfoContainer.Get(typeof(T));

            var userId = getUserKeyFunc != null?getUserKeyFunc.Invoke() : default;

            if (info.IsUpdateAudit)
            {
                if (!fieldValueList.Exists(f => f.Field == "UpdateBy"))
                {
                    fieldValueList.Add("UpdateBy", userId);
                }

                if (!fieldValueList.Exists(f => f.Field == "UpdateAt"))
                {
                    fieldValueList.Add("UpdateAt", DateTime.Now);
                }
            }

            var stringParameter = fieldValueList.Invoke();

            var sql = SqlServerSqlBuilder.UpdateByCondition(info, stringParameter.Sql, condition.ToCondition());

            stringParameter.Parameters.AddDynamicParams(condition.ToParameters());

            return(conn.Execute(sql, stringParameter.Parameters, trans));
        }
예제 #4
0
        private void AddBuildMethod(
            InterfaceTypeDescriptor resultNamedType,
            ClassBuilder classBuilder)
        {
            var responseParameterName = "response";

            var buildMethod = MethodBuilder
                              .New()
                              .SetAccessModifier(AccessModifier.Public)
                              .SetName("Build")
                              .SetReturnType(
                TypeReferenceBuilder.New()
                .SetName(TypeNames.IOperationResult)
                .AddGeneric(resultNamedType.RuntimeType.Name))
                              .AddParameter(
                ParameterBuilder.New()
                .SetType(
                    TypeReferenceBuilder.New()
                    .SetName(TypeNames.Response)
                    .AddGeneric(TypeNames.JsonDocument)
                    .SetName(TypeNames.Response))
                .SetName(responseParameterName));

            var concreteResultType =
                CreateResultInfoName(resultNamedType.ImplementedBy.First().RuntimeType.Name);

            buildMethod.AddCode(
                AssignmentBuilder.New()
                .SetLefthandSide(
                    $"({resultNamedType.RuntimeType.Name} Result, {concreteResultType} " +
                    "Info)? data")
                .SetRighthandSide("null"));

            buildMethod.AddEmptyLine();
            buildMethod.AddCode(
                IfBuilder.New()
                .SetCondition(
                    ConditionBuilder.New()
                    .Set("response.Body is not null")
                    .And("response.Body.RootElement.TryGetProperty(\"data\"," +
                         $" out {TypeNames.JsonElement} obj)"))
                .AddCode("data = BuildData(obj);"));

            buildMethod.AddEmptyLine();
            buildMethod.AddCode(
                MethodCallBuilder.New()
                .SetPrefix("return new ")
                .SetMethodName(
                    TypeNames.OperationResult.WithGeneric(resultNamedType.RuntimeType.Name))
                .AddArgument("data?.Result")
                .AddArgument("data?.Info")
                .AddArgument(_resultDataFactoryFieldName)
                .AddArgument("null"));

            classBuilder.AddMethod(buildMethod);
        }
예제 #5
0
        public static List <T> Fetch <T, T1, T2, T3, T4>(this SqlConnection conn,
                                                         string table,
                                                         string fields,
                                                         Func <T, T1, T2, T3, T4, T> func,
                                                         ConditionBuilder condition,
                                                         SortBuilder sort, SqlTransaction trans = null)
        {
            condition = condition ?? ConditionBuilder.New();
            sort      = sort ?? new SortBuilder();

            var sql = $"SELECT {fields} FROM [{table}] WHERE {condition.ToCondition()} ORDER BY {sort.ToOrderBy()}";

            return(conn.Query(sql, func, condition.ToParameters(), trans).ToList());
        }
예제 #6
0
        public static T FirstOrDefault <T, TPrimaryKey>(
            this SqlConnection conn,
            string table,
            string fields,
            ConditionBuilder condition,
            SortBuilder sort,
            SqlTransaction trans = null)
            where T : IBaseEntity <TPrimaryKey>
        {
            condition = condition ?? ConditionBuilder.New();
            sort      = sort ?? new SortBuilder();

            var sql = SqlServerSqlBuilder.LoadByCondition(table, fields, condition.ToCondition(), sort.ToOrderBy());

            return(conn.QueryFirstOrDefault <T>(sql, condition.ToParameters()));
        }
예제 #7
0
        public static List <T> PageList <T>(this SqlConnection conn, string table, string fields, ConditionBuilder condition, SortBuilder sort,
                                            int pageIndex, int pageSize, out int totalCount, SqlTransaction trans = null)
        {
            condition = condition ?? ConditionBuilder.New();
            sort      = sort ?? new SortBuilder();

            var sql = SqlServerSqlBuilder.PagingSelectWithTotalCount(table, fields, condition.ToCondition(), sort.ToOrderBy(),
                                                                     pageIndex, pageSize);

            var parameters = condition.ToParameters();

            parameters.Add("RecordCount", dbType: DbType.Int32, direction: ParameterDirection.Output);

            var data = conn.Query <T>(sql, parameters, trans);

            totalCount = parameters.Get <int>("RecordCount");
            return(data.ToList());
        }
예제 #8
0
        public static List <T> Fetch <T>(this SqlConnection conn,
                                         ConditionBuilder condition,
                                         SortBuilder sort,
                                         SqlTransaction trans = null)
        {
            condition = condition ?? ConditionBuilder.New();
            sort      = sort ?? new SortBuilder();

            var info = EntityInfoContainer.Get(typeof(T));

            if (info.IsSoftDelete)
            {
                condition = condition.AndEqual("IsDel", false);
            }

            var sql = $"SELECT {info.GetSelectFields()} FROM [{info.TableName}] WHERE {condition.ToCondition()} ORDER BY {sort.ToOrderBy()}";

            return(conn.Query <T>(sql, condition.ToParameters(), trans).ToList());
        }
예제 #9
0
        public static T FirstOrDefault <T, TPrimaryKey>(this SqlConnection conn,
                                                        ConditionBuilder condition,
                                                        SortBuilder sort,
                                                        SqlTransaction trans = null)
            where T : IBaseEntity <TPrimaryKey>
        {
            condition = condition ?? ConditionBuilder.New();
            sort      = sort ?? new SortBuilder();

            var info = EntityInfoContainer.Get(typeof(T));

            if (info.IsSoftDelete)
            {
                condition = condition.AndEqual("IsDel", false);
            }

            var sql = SqlServerSqlBuilder.LoadByCondition(info, condition.ToCondition(), sort.ToOrderBy());

            return(conn.QueryFirstOrDefault <T>(sql, condition.ToParameters()));
        }
        private CodeBlockBuilder EnsureProperNullability(
            string propertyName = _objParamName,
            bool isNonNullType  = false)
        {
            var ifBuilder = IfBuilder
                            .New()
                            .SetCondition(
                ConditionBuilder.New()
                .Set($"!{propertyName}.HasValue"));

            ifBuilder.AddCode(
                isNonNullType
                    ? $"throw new {TypeNames.ArgumentNullException}();"
                    : "return null;");

            var codeBuilder = CodeBlockBuilder.New()
                              .AddCode(ifBuilder)
                              .AddEmptyLine();

            return(codeBuilder);
        }
예제 #11
0
        private static ICode BuildPropertyComparison(
            ITypeDescriptor type,
            string propertyName)
        {
            const string other = nameof(other);

            return(BuildPropertyInternal(type, true));

            ICode BuildPropertyInternal(
                ITypeDescriptor currentType,
                bool isNullable)
            {
                return(currentType switch
                {
                    NonNullTypeDescriptor d =>
                    BuildPropertyInternal(d.InnerType, false),
                    ILeafTypeDescriptor d when d.SerializationType.IsValueType =>
                    CodeInlineBuilder
                    .New()
                    .SetText($"{propertyName} == {other}.{propertyName}"),
                    INamedTypeDescriptor when isNullable =>
                    ConditionBuilder
                    .New()
                    .Set($"({propertyName} is null && {other}.{propertyName} is null) ||" +
                         $"{propertyName} != null && {propertyName}.{nameof(Equals)}(" +
                         $"{other}.{propertyName})"),
                    INamedTypeDescriptor =>
                    MethodCallBuilder
                    .Inline()
                    .SetMethodName(propertyName, nameof(Equals))
                    .AddArgument($"{other}.{propertyName}"),
                    ListTypeDescriptor =>
                    MethodCallBuilder
                    .Inline()
                    .SetMethodName(TypeNames.SequenceEqual)
                    .AddArgument(propertyName)
                    .AddArgument($"{other}.{propertyName}"),
                    _ => throw new ArgumentOutOfRangeException()
                });
            }
 private TryCatchBuilder CreateBuildDataSerialization()
 {
     return(TryCatchBuilder
            .New()
            .AddTryCode(
                IfBuilder
                .New()
                .SetCondition(
                    ConditionBuilder
                    .New()
                    .Set("response.Body != null"))
                .AddCode(
                    IfBuilder
                    .New()
                    .SetCondition(
                        ConditionBuilder
                        .New()
                        .Set("response.Body.RootElement.TryGetProperty(" +
                             $"\"data\", out {TypeNames.JsonElement} " +
                             "dataElement) && dataElement.ValueKind == " +
                             $"{TypeNames.JsonValueKind}.Object"))
                    .AddCode("data = BuildData(dataElement);"))
                .AddCode(
                    IfBuilder
                    .New()
                    .SetCondition(
                        ConditionBuilder
                        .New()
                        .Set(
                            "response.Body.RootElement.TryGetProperty(" +
                            $"\"errors\", out {TypeNames.JsonElement} " +
                            "errorsElement)"))
                    .AddCode($"errors = {TypeNames.ParseError}(errorsElement);")))
            .AddCatchBlock(
                CatchBlockBuilder
                .New()
                .SetExceptionVariable("ex")
                .AddCode(CreateDataError())));
 }
        private void AddBuildMethod(
            InterfaceTypeDescriptor resultNamedType,
            ClassBuilder classBuilder)
        {
            var buildMethod = classBuilder
                              .AddMethod()
                              .SetAccessModifier(AccessModifier.Public)
                              .SetName("Build")
                              .SetReturnType(
                TypeReferenceBuilder
                .New()
                .SetName(TypeNames.IOperationResult)
                .AddGeneric(resultNamedType.RuntimeType.Name));

            buildMethod
            .AddParameter(_response)
            .SetType(TypeNames.Response.WithGeneric(TypeNames.JsonDocument));

            var concreteResultType =
                CreateResultInfoName(resultNamedType.ImplementedBy.First().RuntimeType.Name);

            buildMethod.AddCode(
                AssignmentBuilder
                .New()
                .SetLefthandSide(
                    $"({resultNamedType.RuntimeType.Name} Result, {concreteResultType} " +
                    "Info)? data")
                .SetRighthandSide("null"));
            buildMethod.AddCode(
                AssignmentBuilder
                .New()
                .SetLefthandSide(
                    TypeNames.IReadOnlyList
                    .WithGeneric(TypeNames.IClientError)
                    .MakeNullable() + " errors")
                .SetRighthandSide("null"));

            buildMethod.AddEmptyLine();
            buildMethod.AddCode(
                TryCatchBuilder
                .New()
                .AddTryCode(
                    IfBuilder
                    .New()
                    .SetCondition(
                        ConditionBuilder
                        .New()
                        .Set("response.Body != null"))
                    .AddCode(
                        IfBuilder
                        .New()
                        .SetCondition(
                            ConditionBuilder
                            .New()
                            .Set("response.Body.RootElement.TryGetProperty(" +
                                 $"\"data\", out {TypeNames.JsonElement} " +
                                 "dataElement) && dataElement.ValueKind == " +
                                 $"{TypeNames.JsonValueKind}.Object"))
                        .AddCode("data = BuildData(dataElement);"))
                    .AddCode(
                        IfBuilder
                        .New()
                        .SetCondition(
                            ConditionBuilder
                            .New()
                            .Set(
                                "response.Body.RootElement.TryGetProperty(" +
                                $"\"errors\", out {TypeNames.JsonElement} " +
                                "errorsElement)"))
                        .AddCode($"errors = {TypeNames.ParseError}(errorsElement);")))
                .AddCatchBlock(
                    CatchBlockBuilder
                    .New()
                    .SetExceptionVariable("ex")
                    .AddCode(
                        AssignmentBuilder.New()
                        .SetLefthandSide("errors")
                        .SetRighthandSide(
                            ArrayBuilder.New()
                            .SetDetermineStatement(false)
                            .SetType(TypeNames.IClientError)
                            .AddAssigment(
                                MethodCallBuilder
                                .Inline()
                                .SetNew()
                                .SetMethodName(TypeNames.ClientError)
                                .AddArgument("ex.Message")
                                .AddArgument("exception: ex"))))));

            buildMethod.AddEmptyLine();
            buildMethod.AddCode(
                MethodCallBuilder
                .New()
                .SetReturn()
                .SetNew()
                .SetMethodName(TypeNames.OperationResult)
                .AddGeneric(resultNamedType.RuntimeType.Name)
                .AddArgument("data?.Result")
                .AddArgument("data?.Info")
                .AddArgument(_resultDataFactory)
                .AddArgument("errors"));
        }
예제 #14
0
        public static ClassBuilder AddEquality(
            this ClassBuilder builder,
            string typeName,
            IReadOnlyList <PropertyDescriptor> properties)
        {
            const string obj   = nameof(obj);
            const string other = nameof(other);

            builder.AddImplements(TypeNames.IEquatable.WithGeneric(typeName));

            builder
            .AddMethod(nameof(IEquatable <object> .Equals))
            .SetPublic()
            .SetOverride()
            .SetReturnType(TypeNames.Boolean)
            .AddParameter(obj, x => x.SetType(TypeNames.Object.MakeNullable()))
            .AddCode(CodeBlockBuilder
                     .New()
                     .AddCode(IfBuilder
                              .New()
                              .SetCondition(MethodCallBuilder
                                            .Inline()
                                            .SetMethodName(nameof(ReferenceEquals))
                                            .AddArgument("null")
                                            .AddArgument(obj))
                              .AddCode("return false;"))
                     .AddEmptyLine()
                     .AddCode(IfBuilder
                              .New()
                              .SetCondition(MethodCallBuilder
                                            .Inline()
                                            .SetMethodName(nameof(ReferenceEquals))
                                            .AddArgument("this")
                                            .AddArgument(obj))
                              .AddCode("return true;"))
                     .AddEmptyLine()
                     .AddCode(IfBuilder
                              .New()
                              .SetCondition($"{obj}.GetType() != GetType()")
                              .AddCode("return false;"))
                     .AddEmptyLine()
                     .AddLine($"return Equals(({typeName}){obj});"));

            ConditionBuilder equalCondition =
                ConditionBuilder
                .New()
                .SetReturn()
                .SetDetermineStatement();

            if (properties.Count == 0)
            {
                equalCondition.And("true");
            }
            else
            {
                foreach (PropertyDescriptor property in properties)
                {
                    equalCondition.And(ConditionBuilder
                                       .New()
                                       .Set(BuildPropertyComparison(property.Type, property.Name)));
                }
            }

            builder
            .AddMethod(nameof(IEquatable <object> .Equals))
            .SetPublic()
            .SetReturnType(TypeNames.Boolean)
            .AddParameter(other, x => x.SetType(typeName.MakeNullable()))
            .AddCode(CodeBlockBuilder
                     .New()
                     .AddCode(IfBuilder
                              .New()
                              .SetCondition(MethodCallBuilder
                                            .Inline()
                                            .SetMethodName(nameof(ReferenceEquals))
                                            .AddArgument("null")
                                            .AddArgument(other))
                              .AddCode("return false;"))
                     .AddEmptyLine()
                     .AddCode(IfBuilder
                              .New()
                              .SetCondition(MethodCallBuilder
                                            .Inline()
                                            .SetMethodName(nameof(ReferenceEquals))
                                            .AddArgument("this")
                                            .AddArgument(other))
                              .AddCode("return true;"))
                     .AddEmptyLine()
                     .AddCode(IfBuilder
                              .New()
                              .SetCondition($"{other}.GetType() != GetType()")
                              .AddCode("return false;"))
                     .AddEmptyLine()
                     .AddCode(equalCondition));

            builder
            .AddMethod(nameof(GetHashCode))
            .SetPublic()
            .SetOverride()
            .SetReturnType(TypeNames.Int32)
            .AddCode(HashCodeBuilder
                     .New()
                     .AddProperties(properties));

            return(builder);
        }