1

I have code using entity framework as shown below. I am getting the following excpetion. What is the reason for this? How to overcome this?

The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'MyEntityDataModelEDM.Payment'.

Note: I wrote this code based on the reply in Context Per Request: How to update Entity

enter image description here

CODE

public class MyPaymentRepository
{
    private string connectionStringVal;
    public MyPaymentRepository()
    {
        SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
        sqlBuilder.DataSource = ".";
        sqlBuilder.InitialCatalog = "LibraryReservationSystem";
        sqlBuilder.IntegratedSecurity = true;

        // Initialize the EntityConnectionStringBuilder.
        EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
        entityBuilder.Provider = "System.Data.SqlClient";
        entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
        entityBuilder.Metadata = @"res://*/MyEDMtest.csdl|res://*/MyEDMtest.ssdl|res://*/MyEDMtest.msl";

        connectionStringVal = entityBuilder.ToString();
    }




    public MyEntityDataModelEDM.Payment GetPaymentByID(int paymentID)
    {
        MyEntityDataModelEDM.Payment payment;
        using (var myDatabaseContext = new MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
        {

            Func<MyEntityDataModelEDM.Payment, bool> predicate = (p => p.PaymentID == paymentID);
            payment = myDatabaseContext.Payments.SingleOrDefault(predicate);
        }
        return payment;
    }


    public void UpdateDBWithContextChanges(MyEntityDataModelEDM.Payment paymentEntity)
    {
        using (var myDatabaseContext = new MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
        {
            myDatabaseContext.ObjectStateManager.ChangeObjectState(paymentEntity, System.Data.EntityState.Modified);
            myDatabaseContext.SaveChanges();
        }
    }


}

CLIENT

    static void Main(string[] args)
    {

        MyRepository.MyPaymentRepository rep = new MyRepository.MyPaymentRepository();


        MyEntityDataModelEDM.Payment p2 =  rep.GetPaymentByID(1);
        p2.PaymentType = "CHANGE";
        rep.UpdateDBWithContextChanges(p2);


    }

REFERENCE:

  1. The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418

1 Answers1

0

You did not attach it to the context first. See the answer to the referenced question.

Community
  • 1
  • 1
Kit
  • 20,354
  • 4
  • 60
  • 103