Skip to content

Instantly share code, notes, and snippets.

@sniffdk
Last active May 3, 2019 11:41
Show Gist options
  • Save sniffdk/92895a5bcf9b5aa975d247c68101ee10 to your computer and use it in GitHub Desktop.
Save sniffdk/92895a5bcf9b5aa975d247c68101ee10 to your computer and use it in GitHub Desktop.
Wrap an Examine SearchResult in IPublishedContent
public class DetachedIdPublishedContent : DetachedPublishedContent
{
public DetachedIdPublishedContent(int id, Guid key, string name, PublishedContentType contentType, IEnumerable<IPublishedProperty> properties, IPublishedContent containerNode = null, int sortOrder = 0, bool isPreviewing = false)
: base(key, name, contentType, properties, containerNode, sortOrder, isPreviewing)
{
Id = id;
}
public override int Id { get; }
}
public class SearchResultPublishedContent<TType> where TType : class, IPublishedContent
{
private readonly SearchResult _searchResult;
public int DocId => _searchResult.DocId;
public int Id => _searchResult.Id;
public Guid Key => PublishedContent.GetKey();
public float Score => _searchResult.Score;
public TType PublishedContent;
public SearchResultPublishedContent(SearchResult searchResult)
{
Enum.TryParse<PublishedItemType>(searchResult["__IndexType"], true, out var publishedItemType);
var publishedContentType = PublishedContentType.Get(publishedItemType, typeof(TType).Name);
var properties = publishedContentType
.PropertyTypes
.Where(x => searchResult[x.PropertyTypeAlias] != null)
.Select(x => new DetachedPublishedProperty(x, searchResult[x.PropertyTypeAlias]));
var detachedPublishedContent = new DetachedIdPublishedContent(searchResult.Id, new Guid(searchResult["__Key"]), searchResult["nodeName"], publishedContentType, properties);
PublishedContent = ResolverBase<PublishedContentModelFactoryResolver>
.Current
.Factory
.CreateModel(detachedPublishedContent)
.OfType<TType>();
_searchResult = searchResult;
}
public TValue GetValue<TValue>(Expression<Func<TType, TValue>> selector)
{
if (!(selector.Body is MemberExpression body))
{
throw new ArgumentException("Not a property expression.", nameof(selector));
}
return GetValue<TValue>(body.Member.Name);
}
public TValue GetValue<TValue>(string alias)
{
return PublishedContent.GetPropertyValue<TValue>(alias);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment