Reflection is slow (slow subjective), and if you want to avoid it, you need to get rid of such code, as shown below:
Type type = entityEntry.Entity.GetType(); if (type.GetProperty("InsertedBy") != null)
Even if this was not the case, the code above is still buggy, because the programmer may mistakenly write InsertBy instead of InsertedBy . This can be easily avoided using the compiler using the approach below.
Use the interface and implement it in all objects requiring audit.
public interface IAuditable { string InsertedBy { get; set; } // ... other properties } public class SomeEntity : IAuditable { public string InsertedBy { get; set; } } public class Auditor<TAuditable> where TAuditable : IAuditable { public void ApplyAudit(TAuditable entity, int userId) {
As mentioned in the comments, you will get compiler support, and reflections are no longer used. I would take another step and not go through int userId . I will give the code to define userId and put it in this class. Thus, the class is self-sufficient, and clients do not need to provide it with this information.
Using:
var e = new SomeEntity(); var auditor = new Auditor<SomeEntity>(); auditor.ApplyAudit(e, 1);
Or use it out of context:
public override int SaveChanges() { var auditables = ChangeTracker.Entries().Where(e => e.State == System.Data.Entity.EntityState.Added || e.State == System.Data.Entity.EntityState.Modified) .OfType<IAuditable>(); var auditor = new Auditor<IAuditable>(); foreach (var entry in auditables) {
This means that all entities that are subject to audit will need to implement the IAuditable interface. EF generates partial classes for your objects, but does not modify these partial classes, because the next time you run a custom tool, it will be destroyed.
Instead, create another incomplete class with the same name and implement IAuditable .
public partial class SomeEntity : IAuditable {}
An even better approach is to create a custom T4 template, so it creates a partial class with code : IAuditable . Please see this article to learn how to do this.