How can I get an object's values before the object is edited in a database?

368 views Asked by At

I am coding a Web API 2 webservice, and would like some help in getting an object's values before an object is edited in a DbSet.

I have done some research and I believe that I need to use the ObjectStateEntry object. However, I am not sure on how to get the object's values using the ObjectStateEntry object.

Here is a simple put function with some code that I think should work:

// PUT: api/Templates1/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutTemplate(int id, Template template)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    if (id != template.id)
    {
        return BadRequest();
    }

    ObjectStateEntry myObjectState = db.ObjectStateManager.GetObjectStateEntry(template);
    var originalValues = myObjectState.OriginalValues;

    db.Entry(template).State = EntityState.Modified;

    try
    {
        await db.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!TemplateExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return StatusCode(HttpStatusCode.NoContent);
}

I am getting the following error:

'DataService.Context.DataServiceContext' does not contain a definition for 'ObjectStateManager' and no extension method 'ObjectStateManager' accepting a first argument of type 'DataService.Context.DataServiceContext' could be found (are you missing a using directive or an assembly reference?)

Can someone please help me get the values of an object, before the object is edited in a database?

1

There are 1 answers

0
Jonathan Magnan On

The ObjectStateManager is a property from the ObjectContext

using (var ctx = new TestContext())
{
    var first = ctx.Entity_Basics.First();
    var objectStateEntry = ((IObjectContextAdapter)ctx).ObjectContext.ObjectStateManager.GetObjectStateEntry(first);


    //ctx.Entity_Basics.Delete();
    //ctx.Entity_Basics.Update(x => new Entity_Basic() { ColumnInt = 2 });
}

If you need more help, you can check the source code of my EntityFramework Plus Audit library