0

I am trying to override SaveChanges() method from DbContext for auditing purpose. When I am overriding it in my application under some partial class MyEntities inheriting DbContext, it works fine without any issue. Also MyEntities class contains few DbSets connecting various DB Tables.

But as soon as Entity Framework is updated, Context.cs file gets updated as it's auto-generated, due to which I am loosing my code.

Is there any way to keep this overidden function in some other class file within /outside same namespace? I tried to create another class file and kept my custom code to override SaveChanges() and perform action on DbSet<>, But this method is not getting called and base SaveChanges() is executed.

I appreciate any suggestions to overcome this. Let me know if anything is required.

Thanks, Pankaj

Pankajyt
  • 85
  • 1
  • 7
  • you obviously mentioned the ***partial class*** in the question title, why not use that? Create a separate file in which you define the partial class of your dbcontext, then you can override the `SaveChanges` method there safely. – King King Oct 13 '15 at 16:57
  • @KingKing : I have created saperate file, implemented partial class, and I did override SaveChanges(). But when I am inheriting like newClass:DbContext, I dont have access to DbSet which is required to addObject for saving purpose. And when I am inheriting like newClass:MyEntities, I am not getting any compilation errors or warnings, build is successful But still overridden method is not getting called and app is executing only base method. – Pankajyt Oct 13 '15 at 17:06
  • well the partial class should not have any inheriting instruction. That is already done in the auto-generated class. Remove the `:DbContext` and it will be fine. – King King Oct 13 '15 at 17:09
  • 1
    Yes right. I will make changes. Thanks King. :) – Pankajyt Oct 13 '15 at 17:14
  • It worked.. Now I came across another issue. For ObjectStateEntry, I am unable to retrieve original values for MODIFIED as they are still retrieving currentValues only. Does anyone have any solution/suggestions? – Pankajyt Oct 14 '15 at 18:08
  • well, you should ask that in another question, maybe you do something wrong in the overridden `SaveChanges`? This question asked just about partial class and you got the answer. – King King Oct 14 '15 at 19:58
  • Hmm.. Figured it out. Disabled AUtoDetectChanges in repository and just used detectChnages() before GetModifiedEntries... – Pankajyt Oct 16 '15 at 17:06

0 Answers0