Entity Framework: ObjectStateEntry error

.net c# entity-framework

Question

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
1
1
5/23/2017 12:07:02 PM

Popular Answer

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

0
5/23/2017 12:19:42 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow