-
Notifications
You must be signed in to change notification settings - Fork 17
Getting Started
To start working with EFHooks is easy. You need the NuGet package manager available from http://www.nuget.org
Once NuGet is installed, right click the project references, select "Manage NuGet Packages" and install EFHooks
When NuGet has installed EFHooks, derive your DbContext class from the EFHooks.HookedDbContext
instead of the standard DbContext
in Entity Framework and you can begin writing hooked code.
public class AppContext : EFHooks.HookedDbContext
{
public AppContext() : base()
{
this.RegisterHook(new AuditPreInsertHook()); // Registering a hook from the constructor.
}
public DbSet<User> Users { get; set; }
public DbSet<Post> Posts { get; set; }
}
The design goal of EFHooks was to separate concerns and make it possible to write strongly typed hooks that are easy to unit test without having to use a DbContext.
To illustrate this, lets create that AuditPreInsertHook we saw in the previous section.
Hooks will usually be derived from one of the six strongly typed hook base classes.
PreInsertHook<TEntity>
PreUpdateHook<TEntity>
PreDeleteHook<TEntity>
PostInsertHook<TEntity>
PostUpdateHook<TEntity>
PostDeleteHook<TEntity>
First look at what the entity class looks like:
public interface IAudited {
DateTime CreatedAt { get; set; }
string CreatedBy { get; set; }
}
public class User : IAudited {
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; } // implements IAudited
public string CreatedBy { get; set; } // implements IAudited
}
Before inserting any User
to the database, the CreatedAt and CreatedBy fields must be set to the current Date/Time and currently logged in user name. That is achieved by using a PreInsertHook<TEntity>
from EFHooks.
public class AuditPreInsertHook : PreInsertHook<IAudited> {
public override void Hook(IAudited entity, HookEntityMetadata metadata) {
entity.CreatedAt = DateTime.Now;
entity.CreatedBy = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
}
A few things have just happened here. AuditPreInsertHook implements the PreInsertHook with a type parameter of IAudited. That enables you to write strongly typed code without worrying about handling boxing and unboxing of objects as only IAudited objects will ever be handled by this hook.
Run this code and you'll see that the CreatedAt and CreatedBy fields are filled in by EFHooks before your the object gets inserted to the database.