我有使用实体框架的代码,如下所示。我得到以下异常。这是什么原因?如何克服这一点?
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);
}
参考: