I'm building a site using Kentico Cloud with .Net SDK providing search functionality using the Lucene.Net to store index items.
I would like to create strongly typed model from DeliveryClient.ContentItem in the search implementation.
I have implemented the like that:
var result = await client.GetItemAsync("home");
var item = result.Item; // ContentItem
// ToObject is my own implementation that does the conversion
return item?.ToObject(CustomTypeProvider.GetType(item?.system?.type));
I would much rather use a built-in method to get the strongly typed model than having to use a switch that needs to be updated whenever I add new content types (To The ToObject method).
This question is a migrated from official Kentico Cloud Forum, that would be deleted.
Use ContentItem.CastTo<object>()
method (or DeliveryItemResponse.CastTo<object>()
/ DeliveryItemListingResponse.CastTo<object>()
) method with object
as a generics.
Example with ContentItem.CastTo()
method
var result = await client.GetItemAsync("home");
var item = result.Item; // ContentItem
return item?.CastTo<object>() // Automatically converts to the desired strongly content type