Problems filtering entities from an nhibernate mapping with an IInterceptor
I have a set of entities that implement an interface:
public interf开发者_Go百科ace ILocalised
{
Culture Culture { get; }
}
For lots of complicated reasons I need to filter entities which do not have the correct culture after they are returned back from the DB (i.e. I can't use a Filter). My immediate thought was to create an interceptor that would filter any entities that did not have the correct culture, e.g.
public class LocalisationInterceptor : EmptyInterceptor
{
public override object Instantiate(string clazz, NHibernate.EntityMode entityMode, object id)
{
var entity = base.Instantiate(clazz, entityMode, id); //Returns null already
if ((entity is ILocalised) && false == IsValidCulture((ILocalised)entity))
{
return null;
}
return base.Instantiate(clazz, entityMode, id);
}
public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)
{
if((entity is ILocalised) && false == IsValidCulture((ILocalised)entity))
{
entity = null;
return false;
}
return base.OnLoad(entity, id, state, propertyNames, types);
}
private bool IsValidCulture(ILocalised localisedEntity)
{
return localisedEntity.Culture == Culture.En;
}
}
However so far, what ever method I try to override it will always return the entity.
Does anyone have any ideas how to prevent certain entities from being loaded in an interceptor or any other solutions?
One way is to wrap up the Session using say a Repository. In the Repository.Search method, when the results are returned, do the filtering. So basically you are doing the filtering in your own code after nHibernate is done.
精彩评论