0

Is there a non-complex way of auditing Entity Changes for insert/add? I use the code below to record Entity changes for Edit/Update

var context = new DBEntities(connection());
try
{
    BPCategory Bp = context.BPCategories.First(e => e.id == id);
    Bp.Category = Category;
    Bp.PercentShare = Percent;
    Bp.BPCategory1 = BPCategory;
    Bp.Code = Code;
    Bp.Status = Inactive;


    var objState = context.ObjectStateManager.GetObjectStateEntry(Bp);
    var modProps = objState.GetModifiedProperties();
    foreach (var propName in modProps)
    {
        if (!Equals(objState.OriginalValues[propName], objState.CurrentValues[propName]))
        {
            //save audit
        }
    }
    context.SaveChanges();
}
catch (Exception ex)
{
    throw ex;
}

But i'm struggling when it comes to add/insert. How can i do this for insert/add?

var context = new DBEntities(connection());
BPCategory Bp = new BPCategory
{
    Category = Category,
    PercentShare = PercentShare,
    BPCategory1 = BPCategory,
    Code = Code,
    Status = Inactive
};
context.BPCategories.AddObject(Bp);
context.SaveChanges();
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
onhax
  • 199
  • 12
  • Use database triggers. – jegtugado Oct 11 '18 at 05:47
  • Is there any way i can do this without triggers? I am working on 50+ tables. Triggers would be much of a work in my case – onhax Oct 11 '18 at 05:49
  • You can make a script to create one for each of your tables. There is no need to manually generate one by one. – jegtugado Oct 11 '18 at 05:51
  • @onhax You don't need triggers. The changes will appear *after* you add an object to the context, not before. If you try to find changes right after *creating* the context, you'll find none. If you want to audit changes you should create your own context, override `SaveChanges` and inspect the changed values there. – Panagiotis Kanavos Oct 11 '18 at 06:42
  • @PanagiotisKanavos can you post a sample implementation of your idea based on my example? I would really appreaciate it. – onhax Oct 11 '18 at 07:00
  • @onhax there are a lot of duplicate questions already. Granted, most of them are about EF5. Which is a *very* strong indication that you should upgrade to something newer - EF4 is 7 years old. Check [this one for example](https://stackoverflow.com/questions/26355486/entity-framework-6-audit-track-changes) – Panagiotis Kanavos Oct 11 '18 at 07:01

0 Answers0