NickStrupat / EntityFramework.Triggers

Adds events for entity inserting, inserted, updating, updated, deleting, and deleted
MIT License
373 stars 46 forks source link

BeforeChangeEntry(u).Original throwing error System.TypeInitializationException #29

Closed koertner closed 6 years ago

koertner commented 6 years ago

I have implement the triggers: Triggers<EntityBase>.Inserting += u => { u.Entity.CreationDate = DateTime.Now; u.Entity.LastModifiedDate = DateTime.Now; }; Triggers<EntityBase>.Updating += u => { u.Entity.CreationDate = u.Original.CreationDate; u.Entity.CreatedBy = u.Original.CreatedBy; u.Entity.LastModifiedDate = DateTime.Now; }; Triggers<EntityBase>.Deleting += u => { u.Entity.CreationDate = u.Original.CreationDate; u.Entity.CreatedBy = u.Original.CreatedBy; u.Entity.LastModifiedDate = DateTime.Now; }; Since I cannot inherit from DBContext with Triggers I override Savechanges: public override int SaveChanges() { return this.SaveChangesWithTriggers(base.SaveChanges, acceptAllChangesOnSuccess: true); }

This was all working but now I am getting the below error: For some reason I cannot get access to the Original data. '((EntityFrameworkCore.Triggers.TriggerEntityInvoker<Microsoft.EntityFrameworkCore.DbContext, AMSRR.Main.Interface.ReportType>.BeforeChangeEntry)u).Original' threw an exception of type 'System.TypeInitializationException'

Full Exception: $exception {System.TypeInitializationException: The type initializer for 'EntityFrameworkCore.TypedOriginalValues.OriginalValuesWrapper1' threw an exception. ---> System.TypeLoadException: Declaration referenced in a method implementation cannot be a final method. Type: 'ReportType__OriginalValuesWrapper'. Assembly: 'ReportType__OriginalValuesWrapperAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. at System.Reflection.Emit.TypeBuilder.TermCreateClass(RuntimeModule module, Int32 tk, ObjectHandleOnStack type) at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock() at System.Reflection.Emit.TypeBuilder.CreateTypeInfo() at EntityFrameworkCore.TypedOriginalValues.OriginalValuesWrapper1.GetFactory() at EntityFrameworkCore.TypedOriginalValues.OriginalValuesWrapper1..cctor() --- End of inner exception stack trace --- at EntityFrameworkCore.TypedOriginalValues.OriginalValuesWrapper1.Create(EntityEntry originalValues) at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Lazy1.CreateValue()

Any ideas on what is going wrong?

NickStrupat commented 6 years ago

Your properties all need to be virtual for the original values to work. I agree that this is not obvious nor easy to debug. I hope to make a fix soon.

koertner commented 6 years ago

Works Great....Thanks