How to pass a decimal type variable to a string type sql command with decimal separator "."?

Asked

Viewed 50 times

1

I have the following Model class:

public class ModelTransaction
    {

        public int Id { get; set; }

        [Required(ErrorMessage = "Informe a data")]
        public string Date { get; set; }

        [Required(ErrorMessage = "Informe o valor")]
        public decimal Value { get; set; }

        [Required(ErrorMessage = "Informe a descrição")]
        public string Description { get; set; }

        public TransactionType Type { get; set; }
        public ModelUser User { get; set; }
        public ModelAccount Account { get; set; }
        public ModelAccountingPlan AccountingPlan { get; set; }
    }

And I have the following method for accessing the Mysql database (UPDATE command):

public void Update()
        {
        StringBuilder sql = new StringBuilder();

        string loggedIdUser = HttpContextAccessor.HttpContext.Session.GetString("IdUsuarioLogado");

        sql.Append(" UPDATE Transacoes SET ");
        sql.Append($" Data_Transacao = '{Convert.ToDateTime(Date).ToString("yyyy/MM/dd")}', ");
        sql.Append($" Tipo_Transacao = {ConvertHelpers.ToInt32(Type)}, ");
        sql.Append($" Descricao_Transacao = {Description}, ");
        sql.Append($" Valor_Transacao = {Value}, ");
        sql.Append($" Id_Conta = {Account.Id}, ");
        sql.Append($" Id_PlanoContas = {AccountingPlan.Id} ");

        sql.Append($" WHERE Id_PlanoContas = {Id}");
        sql.Append($" AND Id_Usuario = {User.Id}");

        DalFinances dalFinances = new DalFinances();
        dalFinances.ExecuteSql(sql.ToString());
    }

Before passing my Value variable to the command, the value contained in it is with the correct decimal separator for the Mysql command, i.e., with the separator "." (dot). However, when passing this value to the string, the separator becomes "," (comma), causing it not to be well interpreted by Mysql. The server is running with the language settings and globalization as en-BR, and thus uses the comma as the default separator.

However, is there any way to 'circumvent' this question, causing this variable to be passed with a dot instead of a comma?

1 answer

2


Use one of the method overloads Tostring.

You can do:

sql.Append($" Valor_Transacao = {Value.ToString(CultureInfo.InvariantCulture)}, ");

or else:

sql.Append($" Valor_Transacao = '{Value.ToString("0.00")}', ");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.