我有一個存儲庫類,如下所示。有一種獲取實體對象的方法 - GetPaymentByID。我正在檢索Payment對象並對其PaymentType屬性進行更改。但這並不反映在數據庫中。我知道原因 - SaveContextChanges方法使用新的上下文。我需要用上下文請求的方法。因此,我正在每種方法中創建新的上下文。每個請求的上下文背景:如何更新實體
在這種情況下,如何修改代碼以成功更新數據庫?
注意:客戶端程序不應該使用ObjectContext,因爲存儲庫可以使用另一個不使用實體框架的存儲庫進行更改。
注意: 「一個DataContext是輕量級的,不貴創建」
namespace MyRepository
{
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 myObjectContext2 = new MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
{
Func<MyEntityDataModelEDM.Payment, bool> predicate = (p => p.PaymentID == paymentID);
payment = myObjectContext2.Payments.SingleOrDefault(predicate);
}
return payment;
}
public void SaveContextChanges(MyEntityDataModelEDM.Payment paymentEntity)
{
using (var myObjectContext = new MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
{
myObjectContext.SaveChanges();
}
}
}
}
客戶
MyRepository.MyPaymentRepository rep = new MyRepository.MyPaymentRepository();
MyEntityDataModelEDM.Payment p2= rep.GetPaymentByID(1);
p2.PaymentType = "TeSSS";
rep.SaveContextChanges(p2);
READING
Entity Framework 4.1: how to work with per call life time data context?
Attaching and detaching entities from context correctly in EF4.1
Context lifetime management in repository and unit of work pattern
EF4 - Context.Entry isn't available to change an Entity State
請看新行MyEntityDataModelEDM.LibraryReservationSystemEntities()。我正在創造一個新的環境,不是嗎?這個上下文如何能夠意識到前一個上下文對象中所做的更改? – Lijo 2012-07-18 13:33:34
將狀態設置爲'Modified'可以告訴上下文該實體已被修改,並且應該在數據庫中進行更新。這個對象來自哪裏並不重要。 – 2012-07-18 14:28:58
我在這種方法中出現錯誤。請參閱http://stackoverflow.com/questions/11576911/entity-framework-objectstateentry-error?lq=1 – Lijo 2012-07-20 10:46:59