How to get the GUID of a node
c
In a class using IUmbracoContextFactory, I'm trying to get the Guid of a node for later use, but all I get is a load of 00000's. I've tried many things but none work. I think this should work but it doesn't:
Copy code
var orderConfirmedGuid = siteRoot.DescendantsOrSelf<GeneralPage>().Where(x => x.Name == "Order Confirmed").FirstOrDefault().GetUdi().AsGuid();
I can get the Id, so I know the Name string is correct, but not the Guid. Any ideas? Thanks.
a
Get the .Key šŸ™‚
instead of .GetUdi()
a
And remember null checks for
.FirstOrDefault()
I know this wasn't part of your question, but also some additional tips: - calls to any Descendant(s) method can be pretty bad for performance for big sites. Might be worth looking for a better way to archive what you're trying to do - although not always there is one - a call to
.Where
followed by a call to
FirstOrDefault
can typically be combined - eg. such as
.FirstOrDefault(x => x.Name == "Order Confirmed")
. So if we look past the potential issue with iterating trough descendants, your code could look as:
Guid? orderConfirmedGuid = siteRoot.DescendantsOrSelf<GeneralPage>().FirstOrDefault(x => x.Name == "Order Confirmed")?.Key;
j
In the case of the latter, for performance too
Where()
has to iterate everything,
FirstOrDefault()
returns as soon as it finds a match.
a
Exactly. I should've written why that matter :p
c
Thanks. I had
Copy code
OrderConfirmedGuid = siteRoot.DescendantsOrSelf<GeneralPage>().Where(x => x.Name == "Order Confirmed").FirstOrDefault().Key.AsGuid();
but now I have
Copy code
OrderConfirmedGuid = siteRoot.DescendantsOrSelf<GeneralPage>().FirstOrDefault(x => x.Name == "Order Confirmed").Key.AsGuid();
šŸ™‚
d
Ooh til why to use FirstOrDefault
a
@Craig100
.Key
returns a GUID, so the extra
.AsGuid()
shouldn't be necessary (I'm not exacly sure what it does)
j
Copy code
csharp
public static Guid AsGuid(this object value) => value is Guid guid ? guid : Guid.Empty;
😬
251 Views