我有一个存储库类,如下所示。有一种获取实体对象的方法 - GetPaymentByID。我正在检索Payment对象并对其PaymentType属性进行更改。但这并没有反映在数据库中。我知道原因 - SaveContextChanges方法使用新的上下文。
我需要使用每个请求的上下文方法。因此,我在每种方法中创建新的上下文。
在这种情况下,如何修改代码以成功更新数据库?
注意:客户端程序不应使用ObjectContext,因为存储库可以使用另一个不使用Entity Framework 的存储库进行更改。
注意:“ 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);
阅读
答案 0 :(得分:2)
您需要添加(如果数据是新的)或附加(如果数据被编辑)对象到上下文:
这些方面的东西:
public void SaveContextChanges(MyEntityDataModelEDM.Payment paymentEntity)
{
using (var myObjectContext = new MyEntityDataModelEDM.LibraryReservationSystemEntities(connectionStringVal))
{
// use your own logic for determining a "new" entity
myObjectContext.Entry(paymentEntity).State =
(paymentEntity.PaymentID == default(int)) ?
EntityState.Added :
EntityState.Modified;
myObjectContext.SaveChanges();
}
}