1

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

  1. 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

  2. Best way to initialize an entity framework context?

  3. Entity Framework 4.1: how to work with per call life time data context?

  4. Attaching and detaching entities from context correctly in EF4.1

  5. Context lifetime management in repository and unit of work pattern

  6. Entity Framework Multiple Object Contexts

  7. EF4 - Context.Entry isn't available to change an Entity State

Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418

1 Answers1

2

You need to add (if the data is new) or attach (if the data is edited) the object to the context:

http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx

Something along these lines:

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();
    }
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Please see the line new MyEntityDataModelEDM.LibraryReservationSystemEntities(). I am creating a new context here, isn't it? How can this context be aware of the change made in previous context object? – LCJ Jul 18 '12 at 13:33
  • 1
    Setting the state to `Modified` tells the context that the entity is modified and should be updated in the database. It doesn't matter where the object came from. – D Stanley Jul 18 '12 at 14:28
  • I am getting error in this approach. Please see http://stackoverflow.com/questions/11576911/entity-framework-objectstateentry-error?lq=1 – LCJ Jul 20 '12 at 10:46