I can not modify table record using EF

1

I have the following table in SQL, which has those 4 data

Through EF I am trying to update the records say ID 3 to be "40" but for more I try the amount always remains at zero

This is the code I'm using:

/*SE AGREGA SALDO AL SALDO EXISTENTE*/
        public void addSaldo(int idx, int sal)
        {
            var datos = new Saldos
            {
                id = idx,
                Cantidad = sal
            };

            using (var ctx = new ModeloProductos())
            {
                ctx.Entry(datos).State= EntityState.Modified;
                ctx.SaveChanges();
            }
        }
    
asked by Baker1562 25.08.2018 в 11:52
source

1 answer

2

Your problem is conceptual about the EF, to be able to edit an object you must consult it first, in your example you are creating a new one when instantiating with "new Balances". Try the following:

public void addSaldo(int idx, int sal)
{
    using (var ctx = new ModeloProductos())
    {
        var entidad = ctx.Saldos.Where(w => w.id == idx).SingleOrDefault();
        entidad.Cantidad = sal;
        ctx.SaveChanges();
    }
}
    
answered by 25.08.2018 / 14:51
source