Tolist() returning read-only

Asked

Viewed 138 times

1

Follows code:

using (var db = new Entities())
{
    var result = db
        .Tabela1
        .Select(x => new
        {
            x.Coluna1,
            x.Coluna2
        })
        .ToList();

    foreach (var item in result)
    {
        if (item.Coluna1 == string.Empty)
        {
            item.Coluna1 = "Novo Valor";
        }
    }

    db.SaveChanges();
}

Within the if, get error:

The property or indexer ". Column1" cannot be assigned, as it is read-only

Follow another code below (Works with the class "Suaclasse"):

using (var db = new Entities())
{
    var result = db
        .Tabela1
        .Select(x => new SuaClasse //Aqui
        {
            x.Coluna1,
            x.Coluna2
        })
        .ToList();

    foreach (var item in result)
    {
        if (item.Coluna1 == string.Empty)
        {
            item.Coluna1 = "Novo Valor";
        }
    }

    db.SaveChanges();
}

Claase:

public class SuaClasse 
{
    public string Coluna1 { get; set; }
    public string Coluna2 { get; set; }
}

You can make it work without creating the class (example in the first code) ?

2 answers

5


In the first example you are using a anonymous type that has all its members immutable always, so you can not change the content, if you want to do this you have to create a class even, as you did in the second example.

The anonymous type exists essentially as facilitator for query and is not a complete substitute for storing data.

Considering the next question does not need either the anonymous type or a new class. take the type of the entity itself and modify it. By doing this the content is managed by the Entity Framework and will update as you wish. You can even do it on LINQ itself according to Tobias' response with due plugin, even though the code itself does not meet the need.

  • There is no other way without creating the class ? Type Tuple ?

  • 1

    Maybe using a tuple, but I don’t think it’s a good idea in this case, if you’re going to touch the object, create a specific type. Neither anonymous type nor tuple were created for this.

  • So the best way to modify a foreach’s value is to create a new class ?

  • 1

    The way you did in the second code.

3

as Maniero pointed out, you cannot manipulate an anonymous type, however you can assemble your query to meet your condition.

In your specific case, I believe it is to accomplish something similar to a:

UPDATE Tabela1 
SET Coluna1 = 'Novo Valor' 
WHERE Coluna1 = string.Empty

If you are using Entoty Framework, you can install a plugin to perform this Batch Update: Z.EntityFramework.Plus.EF6

Then write the following query:

db.Tabela1
    .Where(x => x.Coluna1 == "")
    .Update(x => new Entity() { Coluna1 = "Novo Valor" });

Browser other questions tagged

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