I have a repository class as shown below. There is a method to get entity object – GetPaymentByID. I am retrieving a Payment object and making a change to its PaymentType property. But this is not reflected in databse. I know the reason – the SaveContextChanges method uses a new context.
I need to use Context Per Request approach. Hence I am creating new context in each method.
In this scenario, how can I modify the code to successfully update the database?
Note: The client program should not use the ObjectContext because the repository can be changed with another repository that does not use Entity Framework.
Note: "A DataContext is lightweight and is not expensive to create"
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();
}
}
}
}
Client
MyRepository.MyPaymentRepository rep = new MyRepository.MyPaymentRepository();
MyEntityDataModelEDM.Payment p2= rep.GetPaymentByID(1);
p2.PaymentType = "TeSSS";
rep.SaveContextChanges(p2);
READING
Add/Attach and Entity States: http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx
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