0

我有一个在我的 NHibernate 项目中实现的 Lucene FT 引擎。我正在尝试做的一件事是支持定期维护,即清除 FT 索引并从持久实体中重建。我构建了一个通用的静态方法PopulateIndex<T>,它可以派生实体的类型,查找全文索引列的属性属性,并将它们存储到 Lucene 目录中。现在,我的问题是如何为该方法提供IEnumerable<T>NHibernate 方面的强类型。

public static void PopulateIndex<T>(IEnumerable<T> entities) where T : class
{
    var entityType = typeof(T);
    if (!IsIndexable(entityType)) return;

    var entityName = entityType.Name;           
    var entityIdName = string.Format("{0}Id", entityName);

    var indexables = GetIndexableProperties(entityType);

    Logger.Info(i => i("Populating the Full-text index with values from the {0} entity...", entityName));
    using (var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30))
    using (var writer = new IndexWriter(FullTextDirectory.FullSearchDirectory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
    {
        foreach (var entity in entities)
        {
            var entityIdValue = entityType.GetProperty(entityIdName).GetValue(entity).ToString();
            var doc = CreateDocument(entity, entityIdName, entityIdValue, indexables);
            writer.AddDocument(doc);
        }
    }
    Logger.Info(i => i("Index population of {0} is complete.", entityName));
}

这是给我 agita 的方法:

public void RebuildIndices()
{
    Logger.Info(i => i("Rebuilding the Full-Text indices..."));
    var entityTypes = GetIndexableTypes();

    if (entityTypes.Count() == 0) return;
    FullText.ClearIndices();
    foreach (var entityType in entityTypes)
    {
        FullText.PopulateIndex(
            _Session.CreateCriteria(entityType)
            .List()
            );
    }
}

看起来这会返回一个强类型List<T>,但事实并非如此。如何获得该强类型列表,或者有替代/更好的方法吗?

4

1 回答 1

1

如果你想获得强类型列表,你应该指定泛型参数。我可以提出两个选择: 避免反思。我PopulateIndex的意思是直接调用每种类型:

public void RebuildIndexes()
{
    Logger.Info(i => i("Rebuilding the Full-Text indices..."));
    FullText.ClearIndices();
    FullText.PopulateIndex(LoadEntities<EntityA>());
    FullText.PopulateIndex(LoadEntities<EntityB>());
    ...
}

private IEnumerable<T> LoadEntities<T>()
{
    _Session.QueryOver<T>().List();
}

或者您可以使用反射调用 PopulateIndex:

public void RebuildIndices()
{
    Logger.Info(i => i("Rebuilding the Full-Text indices..."));
    var entityTypes = GetIndexableTypes();

    if (entityTypes.Count() == 0) return;
    FullText.ClearIndices();
    foreach (var entityType in entityTypes)
    {
        var entityList = _Session.CreateCriteria(entityType).List();
        var populateIndexMethod = typeof(FullText).GetMethod("PopulateIndex", BindingFlags.Public | BindingFlags.Static);
        var typedPopulateIndexMethod = populateIndexMethod.MakeGenericMethod(entityType);
        typedPopulateIndexMethod.Invoke(null, new object[] { entityList });
    }
}
于 2013-03-02T15:51:23.657 回答