Doubt - SaveChanges does not work, only returns 0

4

Follow the code below:

using (var db = new Entities())
{
    var result = db.
        Tabela1
        .Where(x => x.Id == 1)
        .Select(x => new SuaClasse
        {
            Coluna1 = x.Coluna1,
        })
        .FirstOrDefault();

    if (result.Coluna1 != string.Empty)
    {
        result.Coluna2 = "Novo valor";
    }               

    var num = db.SaveChanges(); // aqui retorna 0
}

Class:

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

I just want to select a column and then update column value 2, nothing happens, it only returns 0. What did I do wrong?

    
asked by anonymous 30.10.2017 / 23:45

2 answers

1

Entity Framework does not change anonymous objects , but only changes that which is known and contained in its context. In this code for example, this happens to create a type that Entity does not know.

If you need to change fields individually, you can write update and send Entity Framework execute.

Example:

using (var context = new BloggingContext()) 
{ 
    context.Database.ExecuteSqlCommand( 
        "UPDATE dbo.Blogs SET Name = 'Another Name' WHERE BlogId = 1"); 
}

can also bring information, eg:

using (var context = new BloggingContext()) 
{ 
    var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList(); 
}

and the way that Entity Framework does is to materialize the entire object ( as already explained, contained in its context ) and then you can make changes in the field and have it saved in your code something like this :

using (var db = new Entities())
{
    var result = db.Tabela1.Where(x => x.Id == 1).FirstOrDefault();
    if (result != null)
    {
        result.Coluna2 = "Novo valor";
        var num = db.SaveChanges();
    }
}

30.10.2017 / 23:49
7

You do not need to do a select on an anonymous object or a different class and then perform an update.

Just run the select, change the field, and update it next.

using (var db = new Entities())
{
    var result = db.
        Tabela1
        .Where(x => x.Id == 1).FirstOrDefault();

    if (result.Coluna1 != string.Empty)
    {
        result.Coluna2 = "Novo valor";
    }               

    var num = db.SaveChanges(); // aqui retorna 0
}
    
31.10.2017 / 00:04