简体   繁体   English

使用IInterceptor从Nhibernate映射中过滤实体时出现问题

[英]Problems filtering entities from an nhibernate mapping with an IInterceptor

I have a set of entities that implement an interface: 我有一组实现接口的实体:

public interface 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 (ie 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, eg 我立即想到的是创建一个拦截器,该拦截器将过滤没有正确文化的任何实体,例如

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. 在Repository.Search方法中,返回结果后,进行过滤。 So basically you are doing the filtering in your own code after nHibernate is done. 因此,基本上,您要在完成nHibernate之后以自己的代码进行过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM