1

我有使用实体框架的代码,如下所示。我得到以下异常。这是什么原因?如何克服这一点?

ObjectStateManager 不包含引用“MyEntityDataModelEDM.Payment”类型对象的 ObjectStateEntry。

注意:我根据每个请求的上下文中的回复编写了此代码:如何更新实体

在此处输入图像描述

代码

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();
        }
    }


}

客户

    static void Main(string[] args)
    {

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


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


    }

参考:

  1. ObjectStateManager 不包含引用对象的 ObjectStateEntry
4

1 回答 1

0

您没有先将其附加到上下文中。请参阅参考问题的答案

于 2012-07-20T13:57:45.073 回答