Created
June 1, 2010 18:06
-
-
Save jfromaniello/421250 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class PreInsertListenerBase<TEntity> : IPreInsertEventListener | |
where TEntity : class | |
{ | |
public virtual bool OnPreInsert(PreInsertEvent @event) | |
{ | |
var entity = @event.Entity as TEntity; | |
return entity != null && OnPreInsert(entity, @event); | |
} | |
protected abstract bool OnPreInsert(TEntity entity, PreInsertEvent @event); | |
protected static void UpdateState(PreInsertEvent @event, | |
Expression<Func<TEntity,object>> propertyExpression) | |
{ | |
var entity = (TEntity)@event.Entity ; | |
ChangeState(@event, propertyExpression, propertyExpression.Compile()(entity)); | |
} | |
protected static void ChangeState(PreInsertEvent @event, | |
Expression<Func<TEntity,object>> propertyExpression, | |
object value) | |
{ | |
var propertyName = TypeUtils.DecodeMemberAccessExpression(propertyExpression).Name; | |
var index = Array.IndexOf(@event.Persister.PropertyNames, propertyName); | |
if (index == -1) return; | |
@event.State[index] = value; | |
} | |
} | |
//Example usage | |
public class PreInsertFoo : PreInsertListenerBase<Foo> | |
{ | |
protected override bool OnPreInsert(Foo entity, PreInsertEvent @event) | |
{ | |
//update the live object in memory | |
entity.SomeData = entity.SomeData.Replace("%js", "'" + @event.Id + "'"); | |
//update the state to persist | |
UpdateState(@event, j => j.SomeData); | |
return false; | |
} | |
} | |
//another example | |
public class PreInsertOfAuditable : PreInsertListenerBase<IAuditable> | |
{ | |
protected override bool OnPreInsert(IAuditable entity, PreInsertEvent @event) | |
{ | |
//update the live object in memory | |
entity.InsertDate = DateTime.Today(); | |
//update the state to persist | |
UpdateState(@event, j => j.InsertDate); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment