Beispiel #1
0
        static (string Sql, DbParam[] Parameters) BuildSqlAndParameters(IDbContext dbContext, FormattableString sql)
        {
            List <string>  formatArgs = new List <string>(sql.ArgumentCount);
            List <DbParam> parameters = new List <DbParam>(sql.ArgumentCount);

            IDatabaseProvider databaseProvider = ((DbContext)dbContext).DatabaseProvider;
            string            parameterPrefix  = "P_";

            foreach (var arg in sql.GetArguments())
            {
                object paramValue = arg;
                if (paramValue == null || paramValue == DBNull.Value)
                {
                    formatArgs.Add("NULL");
                    continue;
                }

                Type paramType = arg.GetType();

                if (paramType.IsEnum)
                {
                    paramType = Enum.GetUnderlyingType(paramType);
                    if (paramValue != null)
                    {
                        paramValue = Convert.ChangeType(paramValue, paramType);
                    }
                }

                DbParam p;
                p = parameters.Where(a => PublicHelper.AreEqual(a.Value, paramValue)).FirstOrDefault();

                if (p != null)
                {
                    formatArgs.Add(p.Name);
                    continue;
                }

                string paramName = databaseProvider.CreateParameterName(parameterPrefix + parameters.Count.ToString());
                p = DbParam.Create(paramName, paramValue, paramType);
                parameters.Add(p);
                formatArgs.Add(p.Name);
            }

            string runSql = string.Format(sql.Format, formatArgs.ToArray());

            return(runSql, parameters.ToArray());
        }