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;
budd开发者_高级运维y.room_id = 2;
db.SaveChanges();
}
it looks like it is related to "id" which is primary identity key.
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.
Possibly you need to add your new buddy to onlines
collection?
db.onlines.Add(buddy); // << this
db.SaveChanges();
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.
精彩评论