C# 返回单个项目时,将Sitecore内容搜索与Lucene一起使用时出错
我正在进行从Wordpress到Sitecore 7.2的博客迁移,并用c编写了一个脚本来创建项目。 为了防止重复的项目,我创建了一个扩展方法来检查我们是否已经有了项目C# 返回单个项目时,将Sitecore内容搜索与Lucene一起使用时出错,c#,linq,lucene,sitecore,sitecore7,C#,Linq,Lucene,Sitecore,Sitecore7,我正在进行从Wordpress到Sitecore 7.2的博客迁移,并用c编写了一个脚本来创建项目。 为了防止重复的项目,我创建了一个扩展方法来检查我们是否已经有了项目 /// <summary> /// Check if item with given name exists as child & if yes,return that item /// </summary> /// <returns></returns> public s
/// <summary>
/// Check if item with given name exists as child & if yes,return that item
/// </summary>
/// <returns></returns>
public static Item GetItemIfExists(this Item parentItem, string itemName)
{
Item childItem = null;
using (var context = Constants.Index.CreateSearchContext())
{
childItem = context.GetQueryable<SearchResultItem>().Where(i => i.Path.Contains(parentItem.Paths.FullPath) && i.Name == itemName).Select(i => (Item)i.GetItem()).FirstOrDefault();
}
return childItem;
}
从Sitecore的内容搜索返回单个项目的最佳方法是什么?尝试使用.where i=>i.Path.ContainsparentItem.Path.FullPath&&i.Name==itemName.Take1.ToList
请记住,查询是在枚举之前组装的,因此,只要您调用ToList或选择查询,查询就会发送到搜索索引并进行枚举,从那时起,您就不能修改已发送的查询,因此linq语句的顺序很重要
您可以在示例中看到,我们在枚举之前调用Take来限制调用
您可以在yourlogs'目录中的search.log'中查看查询之间的差异
如果您以前使用过LinqPad,我建议您使用它可以根据自己的搜索索引试验linq查询
/// <summary>
/// Check if item with given name exists as child & if yes,return that item
/// </summary>
/// <returns></returns>
public static Item GetItemIfExists(this Item parentItem, string itemName)
{
var childItem = new List<Item>();
using (var context = Constants.Index.CreateSearchContext())
{
childItem = context.GetQueryable<SearchResultItem>().Where(i => i.Path.Contains(parentItem.Paths.FullPath) && i.Name == itemName).Select(i => (Item)i.GetItem()).ToList();
}
return childItem.FirstOrDefault();
}