e-on
e-on

Reputation: 1605

Updating a row using entity framework

I'm trying to update a field in a table just after I have added a row in a different table. (The value is just to show that the row has been imported) I thought I was using the right code here, but the bool 'Imported' field isn't updated. Here is the relevant code:

using (DbContext db = new DbContext())
{
    db.Details.Add(details);
    db.SaveChanges();
    newID = details.DetailsID;
    AccessRepository rep = new AccessRepository();
    AccessDetails detailUpdate = rep.GetByID(item.AccessDetailsTableID);
    detailUpdate.Imported = true;
    db.SaveChanges();
}

The first SaveChanges call works, as I'm trying to add a new row, but not the second one. It successfully retrieves the data back from the repository but just doesn't update the value.

Any ideas why it might not be working?

Thanks

Upvotes: 0

Views: 836

Answers (2)

Vlad Bezden
Vlad Bezden

Reputation: 89499

Should you use newId in GetById() method?

using (DbContext db = new DbContext())
{
    db.Details.Add(details);
    db.SaveChanges();
    newID = details.DetailsID;
    AccessRepository rep = new AccessRepository();
    AccessDetails detailUpdate = rep.GetByID(newID);
    detailUpdate.Imported = true;
    db.SaveChanges();
}

Upvotes: 0

musefan
musefan

Reputation: 48415

I think this is because your AccessRepository is using a different data context (db) to the one in scope (in your posted code)

You could try having a SaveChanges method in your AccessRepository which does the same but on the correct data context.

However, the issue with calling two saves is that you loss the single transaction benefits. So if those two updates are to be related you really should only call the SaveChanges once.

I would create an Add method and a Save method in your AccessRepository and then use something like this...

AccessRepository rep = new AccessRepository();
rep.Add(details);
AccessDetails detailUpdate = rep.GetByID(item.AccessDetailsTableID);
detailUpdate.Imported = true;
rep.Save();//this calls SaveChanges on a single data context

hope that helps

Upvotes: 1

Related Questions