Search code examples
c#asp.net-web-apireflectionumbracoumbraco8

Umbraco 8: Get reference to DocumentType definition in WebAPI class


Q) How do I get a reference to a DocumentType definition in my UmbracoAPIController class, so that I can do LINQ queries on the properties?

Background:
I've got a WebAPI endpoint I call from JS, that fetches Book items from my DB. I want to filter based on an input variable, such as ISBN, in my LINQ query. In order to do that, I need to get the DocumentType definition imported in my UmbracoAPIController class.

Trying the below, where Book is the type I want to cast to:

var parent = Umbraco.ContentAtRoot().First().Children().FirstOrDefault(x => x.Name == "Booklist");
if (parent != null) 
{
    var isbn = HttpContext.Current.Request.Params["isbn"];

    var books = parent.Children().Cast<Book>().Where(b => b.Isbn == isbn);

    foreach (var book in books) 
    {
        // Do something here....
    }
}

Breaks with the error:

 The type or namespace name 'Book' could not be found (are you missing a using directive or an assembly reference?)

Note: Please don't tell me I'm just doing everything the 'wrong' way unless you have a clear, better alternative, thank you.


Solution

  • I dont know if this will help but i dont do a direct cast (haven't even tried it) and just work with the default property value direct e.g.

    var books = parent.Children().Where(page => page.HasProperty("Isbn") &&
                                            page.HasValue("Isbn") &&
                                            page.Value<string>("Isbn") == Isbn);
    

    Interested though to find out how a direct cast work.