实体框架:ObjectStateEntry错误 [英] Entity Framework: ObjectStateEntry error
本文介绍了实体框架:ObjectStateEntry错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ObjectStateManager不包含引用MyEntityDataModelEDM.Payment类型的对象的ObjectStateEntry。 p>
注意:根据
解决方案
你没有将它附加到上下文中。 请参阅参考问题的答案。
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
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:
解决方案
You did not attach it to the context first. See the answer to the referenced question.
这篇关于实体框架:ObjectStateEntry错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文