Creating a foreach with result of a query coming from the Entity

1
Hello, I'm trying to make a foreach with a query result, the field I need to go through is a string, but at the time I step into the foreach it is being transformed into another value.

I need to compare two date, in case the conversion of the String field to DateTime is giving error, because as mentioned above the field is being modified at the time it passes in the foreach.

Here is the code in PageModel:

var tp = _context.TarifasPrecosItens.Where(p => p.TarifasPrecosId == tx.Id).First();

foreach(var hora in tp.De)
{
    DateTime horaInicial = Convert.ToDateTime(hora);
    DateTime horaCliente  = Convert.ToDateTime(totalPermanencia);

    if (horaCliente > horaInicial)
    {
        PagamentoTarifaUsada = tx.Descricao + " Acima de " + hora;
        Tarifa = tp.Valor;
        Total = tp.Valor;
    }
} 
    
asked by anonymous 20.06.2018 / 16:00

2 answers

0

I did not leave the answer sooner because it was too full.

The problem occurs because you are returning a single item of value "01:00" and passing this value by foreach will return every char of string , you can see an example here .

To return a list, remove First()

var tp = _context.TarifasPrecosItens.Where(p => p.TarifasPrecosId == tx.Id);

Another thing I would do is to use TryParse to do the conversion, as it is possible to make a treatment in the event of an error, you can use it more or less like this:

foreach (var item in tp)
{
    DateTime horaInicial;
    if (!DateTime.TryParse(item.De, out horaInicial))
    {
        //Tratamento erro
    }

}

From C # 7 it is possible to simplify TryParse as follows

DateTime.TryParse(item.De, out DateTime horaInicial)
    
21.06.2018 / 03:11
0

I believe - well, I believe , because, by the description, you can not understand the problem - that what you want to do is:

var tp = 
    _context
        .TarifasPrecosItens
        .Where(w => Convert.ToDateTime(w.TotalPermanencia) > Convert.ToDateTime(w.De)); 

foreach (var item in tp)
{
    item.PagamentoTarifaUsada = $"{item.Descricao} acima de {item.De}";
    item.Tarifa = item.Total = item.Valor;
}

_context.SaveChanges();
    
20.06.2018 / 17:51