Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Thomas Ravnholt 12 posts 102 karma points
    Sep 27, 2022 @ 17:24
    Thomas Ravnholt
    0

    Correct handling of null while querying?

    Hello. I'm in the process of learning Umbraco, and i've run into an issue that i can't figure out how to handle correctly.

    What i'm a trying to do

    • Find and ancestor of a specific type
    • Use the ancestor to filter a query to find items that contains a specifik value.

    My query

    var uddannelse = Model.Ancestors().OfTypes("uddannelse").FirstOrDefault();
    var medarbejdere = Umbraco.Content(Guid.Parse("e7ab5690-bb1b-48e7-900e-521a22e2c2d2"))
    .ChildrenOfType("medarbejder")
    .Where(x => x.IsVisible()).Where((x => x.Value<bool>("isVejleder") && x.Value<IPublishedContent>("uddannelse").Id == uddannelse.Id));
    

    My current solution where i just wrap everything in an if(), this works but seems clumsy.

    @if(Model.Ancestors().OfTypes("uddannelse").FirstOrDefault() != null){
    
    var uddannelse = Model.Ancestors().OfTypes("uddannelse").FirstOrDefault();
    var medarbejdere = Umbraco.Content(Guid.Parse("e7ab5690-bb1b-48e7-900e-521a22e2c2d2"))
    .ChildrenOfType("medarbejder")
    .Where(x => x.IsVisible()).Where((x => x.Value<bool>("isVejleder") && x.Value<IPublishedContent>("uddannelse").Id == uddannelse.Id));
    
    
    @if(medarbejdere.Any()){
        //do this
    }
    }else{
        //do this
    }
    

    What would be the correct way to do this, and is that a general way to handle possible 'Null' when querying.

  • Huw Reddick 1929 posts 6717 karma points MVP 2x c-trib
    Sep 28, 2022 @ 07:49
    Huw Reddick
    1

    you could reduce the calls to Model.Ancestors by doing

        @{
        var uddannelse = Model.Ancestors().OfTypes("uddannelse").FirstOrDefault();
        if(uddannelse  != null){
    
        var medarbejdere = Umbraco.Content(Guid.Parse("e7ab5690-bb1b-48e7-900e-521a22e2c2d2"))
        .ChildrenOfType("medarbejder")
        .Where(x => x.IsVisible()).Where((x => x.Value<bool>("isVejleder") && x.Value<IPublishedContent>("uddannelse").Id == uddannelse.Id));
    
        if(medarbejdere.Any()){
            //do this
        }
        }else{
            //do this
        }
        }
    
Please Sign in or register to post replies

Write your reply to:

Draft