Update problem with 1 field - EF

1

Follow the code:

using (var db = new Entities())
{
    var t = new MinhaTabela
    {
        MeuCampo= 10
    };
    db.Entry(t).State = EntityState.Modified;
    db.SaveChanges();
}

Table definition:

CREATE TABLE [dbo].[MinhaTabela] (
    [MeuCampo] INT NOT NULL,
    CONSTRAINT [PK_MinhaTabela] PRIMARY KEY CLUSTERED ([MeuCampo] ASC)

After the line: db.SaveChanges(); nothing happens and does not change the value.

I can not change the value 9 to 10. What am I doing wrong?

    
asked by anonymous 08.01.2017 / 03:48

1 answer

3

This code does not change anything. You are creating a new object and trying to save this new object by using an update operation. Because this new object does not yet exist in the database, the update operation fails.

The correct one would be to select the record, update and then save again.

var registro = db.MinhaTabela.FirstOrDefault(a => a.MeuCampo == 9);
registro.MeuCampo = 10;
db.Entry(registro).State = EntityState.Modified;
db.SaveChanges();
    
08.01.2017 / 04:06