I am trying to implement an audit trail in Entity Framework 5.
public class AuditZoneRepository : IAuditZoneRepository
{
private AISDbContext context = new AISDbContext();
public int Save(AuditZone model, ModelStateDictionary modelState)
{
if (model.Id == 0)
{
context.AuditZones.Add(model);
}
else
{
var recordToUpdate = context.AuditZones.FirstOrDefault(x => x.Id == model.Id);
if (recordToUpdate != null)
{
recordToUpdate.Description = model.Description;
recordToUpdate.Valid = model.Valid;
recordToUpdate.ModifiedDate = DateTime.Now;
}
}
try
{
context.SaveChanges();
return 1;
}
catch (Exception ex)
{
modelState.AddModelError("", "Database error has occured. Please try again later");
return -1;
}
}
}
To do so, I need the ObjectStateEntry
for the entity
:
entities.ObjectStateManager.GetObjectStateEntry(changedEntity);
as shown here .
When I try to add this to the save function it says unknown. What is the entities value in my case?
With Georges help I updated my save code as follows,
public int Save(AuditZone model, ModelStateDictionary modelState)
{
if (model.Id == 0)
{
context.AuditZones.Add(model);
}
else
{
var recordToUpdate = context.AuditZones.FirstOrDefault(x => x.Id == model.Id);
if (recordToUpdate != null)
{
recordToUpdate.Description = model.Description;
recordToUpdate.Valid = model.Valid;
recordToUpdate.ModifiedDate = DateTime.Now;
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var entires = objectContext.ObjectStateManager.GetObjectStateEntry(recordToUpdate);
IEnumerable<string> modifiedProperties = entires.GetModifiedProperties();
}
}
try
{
context.SaveChanges();
return 1;
}
catch (Exception ex)
{
modelState.AddModelError("", "Database error has occured. Please try again later");
return -1;
}
}
but when I debug it the modifiedProperties has no results in it? am I putting this code in the wrong place?
Taken from the link you've posted:
"we have to use the ObjectStateManager on ObjectContext."
So, entities
should be an implementation of ObjectContext
.
To convert DbContext
to ObjectContext
use:
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
To get entries use:
var entires = objectContext.ObjectStateManager
.GetObjectStateEntries(EntityState.Unchanged);
More about the ObjectContext
and its relation with DbContext
:
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.