Update problem with 1 field - EF

Asked

Viewed 183 times

1

Follows 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 am not managing to change the value 9 to 10. What I am doing wrong ?

1 answer

3


This code does not modify anything. You are creating a new object and trying to save this new object using an update operation. As this new object does not yet exist in 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();
  • Makes a mistake: The property 'MeuCampo' is part of the object's key information and cannot be modified.

  • 1

    Keys cannot be modified by definition. Just deleting the record and inserting another.

Browser other questions tagged

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