简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM