我在我的NHibernate项目中实现了Lucene FT引擎。我要做的其中一件事是支持定期维护,即清理FT索引并从持久化实体重建。我构建了一个通用静态方法PopulateIndex<T>
,它可以派生实体类型,查找全文索引列的属性属性,并将它们存储到Lucene目录中。我现在的问题是如何从NHibernate方面为方法提供强类型IEnumerable<T>
。
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>
,但事实并非如此。我如何获得强类型列表,或者是否有其他/更好的方法来执行此操作?
答案 0 :(得分: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 });
}
}