state 'can not be assigned to - it is read only - Entity Framework

2

Follow 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 foreach :

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

I get the following from error :

  

status' can not be assigned to - it is read only

Any solution?

UPDATE:

I've tried it this 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 the same error still remains.

    
asked by anonymous 15.01.2017 / 02:41

1 answer

3
  

Why does not it work?

You are returning an object unknown (anonymous ) and its elements are treated as readOnly ( read-only ), so to work bring the object into your totality 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 going in if this is the best way, or your performance is favorable. Another thing never do a search in half, everything to do with filter do before ToList() .

There is a package in the nuget EntityFramework.Extended , it 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" });

15.01.2017 / 02:48