ToList () returning read-only

1

Follow the code below:

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 if , I get error:

  

The property or indexer ".Column1" can not be assigned because it is read-only

Here is another code (Works with class "YourClass"):

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; }
}

Can you make it work without creating the class (example in the first code)?

    
asked by anonymous 30.10.2017 / 22:26

2 answers

4

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

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

Considering the next question does not need anonymous type, nor a new class. get the entity's own type and modify it. By doing this the content is managed by the Entity Framework and will update as desired. You can even do it in LINQ itself according to Tobias' response with the plugin , even though the code itself does not meet the need.

    
30.10.2017 / 22:30
3

As Maniero pointed out, you can not manipulate an anonymous type, but you can mount your query to suit your condition.

In your specific case, I believe it's something like this:

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

If you are using the 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" });
    
31.10.2017 / 01:49