コード例 #1
0
ファイル: SqlProvider.cs プロジェクト: zl33842901/DapperEx
        /// <summary>
        /// 生成列参数和值
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="identityProperty">标识列(没有或批量插入时 这个应为null)</param>
        /// <returns></returns>
        private string FormatInsertParamsAndValues(T entity, PropertyInfo identityProperty)
        {
            var paramSqlBuilder = new StringBuilder(100);
            var valueSqlBuilder = new StringBuilder(100);

            var properties = entity.GetProperties(false);

            var isAppend = false;

            foreach (var property in properties)
            {
                if (property.CustomAttributes.Any(b => b.AttributeType == typeof(IdentityAttribute)))
                {
                    continue;
                }
                bool isJsonColumn = property.CustomAttributes.Any(b => b.AttributeType == typeof(JsonColumnAttribute));//是否是JSON列
                if (isAppend)
                {
                    paramSqlBuilder.Append(",");
                    valueSqlBuilder.Append(",");
                }

                var name   = property.GetColumnAttributeName(Dialect); //带方言符号的名称  如 [Title]
                var namenw = property.Name;                            //不带方言符号的纯名称  如  Title

                paramSqlBuilder.Append(name);

                object paramValue;
                if (isJsonColumn && Dialect.SupportJsonColumn && Dialect.HasSerializer)
                {
                    valueSqlBuilder.Append("@" + namenw + "::jsonb");
                    paramValue = Dialect.Serializer(property.GetValue(entity));
                }
                else
                {
                    valueSqlBuilder.Append("@" + namenw);
                    paramValue = property.GetValue(entity);
                }
                Params.Add("@" + namenw, paramValue);

                isAppend = true;
            }

            return(Dialect.FormatInsertValues(identityProperty?.GetColumnAttributeName(Dialect), paramSqlBuilder.ToString(), valueSqlBuilder.ToString()));

            //string outputString = string.Empty;
            //if(identityProperty != null)
            //{
            //    outputString = $" OUTPUT INSERTED.{identityProperty.GetColumnAttributeName(Dialect)} as insertedid ";
            //}
            //return $"({paramSqlBuilder}) {outputString} VALUES  ({valueSqlBuilder})";
        }