state' cannot be Assigned to -- it is read only - Entity Framework

Asked

Viewed 63 times

2

Follows the code:

var resultado = db.Tabela
        .Where(l => l.Nome == "João")
        .Select(l => new { l.numero, l.cidade, l.estado, l.pais });

I know that in the database has "SP" value of the state field and I want to change the value "SP" to "São Paulo".

Here is the foreach:

foreach (var item in resultado.Where(u => u.estado == "SP"))
{
    item.estado= "São Paulo";
}

I get the following from error:

state' cannot be Assigned to -- it is read only

Some solution?

UPDATE:

I’ve tried that way:

var resultado = db.Tabela
                   .Where(l => l.Nome == "João")
                   .Select(l => new { l.numero, l.cidade, l.estado, l.pais }).ToList();

For:

for (int i = 0; i <resultado.Count; i++)
{
    if (resultado[i].estado== "SP")
    {
        resultado[i].estado= "São Paulo";
    }                    
}

and still remains the same error.

  • 1

    IS Entity Framework?

  • 1

    @Virgilionovic, yes

  • 1

    see if it’s clear...

  • 1

    It was really good @Virgilionovic

1 answer

3


Why doesn’t it work?

It’s returning an object unknown (anonymity) and its elements are treated as readOnly (read-only), then to function bring the object in its entirety without Select, do so:

var resultado = db.Tabela
                  .Where(l => l.Nome == "João" && l.estado == "SP")
                  .ToList();

for (int i = 0; i < resultado.Count(); i++)
{
    resultado[i].estado = "São Paulo";
}

db.SaveChanges(); // salvar as alterações.

I’m not getting into whether this is the best way, or your performance is favorable. Another thing never do a half search, anything you do by filter before the ToList().

There is a package in the Entityframework.Extended., can be used quietly to update isolated fields, with the following syntax for your problem:

db.Tabela
   .Where(l => l.Nome == "João" && l.estado == "SP")
   .Update(w => new Tabela { estado = "São Paulo" });

References:

  • 1

    Thanks for the answer helped here.

Browser other questions tagged

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