Posts Tagged ‘Repository Pattern’

EF 4.2 Update POCO with ObjectContext

I recently worked on a project that used the Entity Framework and T4 POCO generation. I ran into a little snag during the implementation of the Repository pattern that took a few minutes for me to figure so I thought that I would save someone else the time and share here.

First let’s start off with the Interface.

  public interface IRepository : IDisposable
  {
    IQueryable All { get; }
    T GetById(int id);
    void Add(T model);
    void Update(T model);
    void Delete(T model);
    void Save();
  }

Next we’ll look at my first try at the concrete implementation of the Update method. The DataContext is a private property containing a reference to the object context object.

  public class MyRepository : IRepository
  {
    public IQueryable All { get{...} }
    public MyEntity GetById(int id) {...}
    public void Add(MyEntity model) {...}

    public void Update(MyEntity model)
    {
      DataContext.Users.Attach(model);
      if (model.Id == null )
      {
        // no UserId denotes new object to the database.
        DataContext.ObjectStateManager.ChangeObjectState(model, System.Data.EntityState.Added);
      }
      else
      {
        // object is not new. We need to get the original object and apply original values.
        // Applying current or original values, changes the state
        // of the attached object to Modified.
        var originalObject = GetById(model.UserId);
        DataContext.ApplyCurrentValues("MyEntities", originalObject);
      }

      Save();

    }

    public void Delete(MyEntity model) {...}
    public void Save() {...}
  }

Everything looked good to me so I ran a quick test set. To my surprise the Update method was failing. Why would this be? Well as it turns out since I was generating my POCO’s I needed to set the EntityState to Modified manually. So added the line below after the ApplyCurrentValues call.

DataContext.ObjectStateManager.ChangeObjectState(model, System.Data.EntityState.Modified);

I fired up the test cases once again and was happy to see all tests passed.

Well that is it, I hope that this post helps you and others in the future.

Related Posts:

  • No Related Posts