Can't get the ApplyCurrentValues(Entity) to work in Entity Framework 5

10,937

ApplyCurrentValues is an ObjectContext API method, so first you have to gain access to the objectcontext that is wrapped in the DbContext:

odc.Accounts.Attach(new Account { AccountID = account.AccountID });
((IObjectContextAdapter)odc).ObjectContext
    .ApplyCurrentValues("Accounts", account);
odc.SaveChanges();

Note that the wrapped context does not have members like "Accounts", so you have to use the ObjectContext method itself.

But you can do the same using the DbContext API:

var sourceAcc = new Account { AccountID = account.AccountID });
odc.Entry(account).CurrentValues.SetValues(sourceAcc);
Share:
10,937
Cizaphil
Author by

Cizaphil

Am a programmer focusing on the microsoft platform (C#, ASP.NET, ASP.NET MVC, Jquery) for the main time. I love programming and everything about it because am very fascinated in the way its' nuts and bolts work and like working in the ground zero level.

Updated on June 23, 2022

Comments

  • Cizaphil
    Cizaphil almost 2 years

    Comrades, can anyone help me out here, entity framework 5 seems not to have ApplyCurrentValues() method. Is there another way to update the database object in entity framework v5. here is what am trying to do

    odc.Accounts.Attach(new Account { AccountID = account.AccountID });
      odc.Accounts.ApplyCurrentValues(account);
      odc.SaveChanges();
    

    But i have been getting compile error in the ApplyCurrentValues() line

  • Cizaphil
    Cizaphil over 11 years
    Thanks @Gert, the code works now, but why is it that it does'nt work in EF 5 but works in version 4 and below?
  • Gert Arnold
    Gert Arnold over 11 years
    I think you inadvertently started using the DbContext API when switching to EF 5. Check the base type of you odc variable.
  • Ryszard Dżegan
    Ryszard Dżegan over 10 years
    Good answer. I just noticed, that ApplyCurrentValues returns sourceAcc with Modified or Unchanged state depending on the case. It does nothing with account instance which is still Detached. I think it maight be explicitly shown. I'm also bit confused with variable names. In sample with EF5 account represents entity from the database. Previously it represented the detached one.