nLL
nLL

Reputation: 5672

How to update a record by id?

I am very new To EntityFramework and having trouble to understand why first code doesn't update but second does. My aim is to update a record without querying db.

Is it too obvious?

using (CHATDBEntities db = new CHATDBEntities())
    {
        // update buddy
        onlines buddy = new onlines();
        buddy.id = 56;
        buddy.last_seen = DateTime.Now;
        buddy.status = (int)UserStatuses.Status.Chatting;
        buddy.connected_to_id = 34;
        buddy.room_id = 2;

        db.SaveChanges();

    }

    using (CHATDBEntities db = new CHATDBEntities())
    {
        // update buddy
        var buddy = db.onlines.First();
        buddy.last_seen = DateTime.Now;
        buddy.status = (int)UserStatuses.Status.Chatting;
        buddy.connected_to_id = 34;
        buddy.room_id = 2;

        db.SaveChanges();

    }

it looks like it is related to "id" which is primary identity key.

Upvotes: 1

Views: 433

Answers (3)

Jethro
Jethro

Reputation: 5916

The reason is because you need to select the object into the ObjectContect before you can update it. It looks like the only way to update the entity is to first read it.

Please see this other stackoverflow link which answers this.

Upvotes: 0

Coding Flow
Coding Flow

Reputation: 21881

You have to retrieve an entity in order to update it, you can't just create a new one with the same id as a record from the database and expect EF to magically know that it needs to update the database. You could try attaching it to the ObjectContext but that is not how you are supposed to do updates.

Upvotes: 1

a553
a553

Reputation: 509

Possibly you need to add your new buddy to onlines collection?

db.onlines.Add(buddy); // << this
db.SaveChanges();

Upvotes: 0

Related Questions