Expand Minimize

Use EnsureProperty/EnsureProperties to ensure a property is loaded.

PnP has an implementations to ensure properties are loaded correctly against the object. This process is also optimised to minimise calls.

CheckId SPC029016
TypeName UseEnsureProperty
Severity Warning
Type Assembly

Standard SharePoint CSOM

// Implementation taken from PnP Core as example
var dirty = false;
foreach (Expression<Func<T, object>> expression in propertySelector)
{
    if (expression.Body.NodeType == ExpressionType.Call && expression.Body is MethodCallExpression)
    {
        var body = (MethodCallExpression) expression.Body;
        if (body.Method.IsGenericMethod &&
            body.Method.DeclaringType == typeof (ClientObjectQueryableExtension) &&
            (body.Method.Name == "Include" || body.Method.Name == "IncludeWithDefaultProperties"))
        {
            if (body.Arguments.Count != 2)
            {
                throw new Exception("Invalid arguments number");
            }

            clientObject.Context.Load(clientObject, expression);
            dirty = true;
        }
        else
        {
            throw new Exception("Only 'Include' and 'IncludeWithDefaultProperties' methods are supported.");
        }
    }
    else if (!clientObject.IsPropertyAvailable(expression) && !clientObject.IsObjectPropertyInstantiated(expression))
    {
        clientObject.Context.Load(clientObject, expression);
        dirty = true;
    }
    else if (clientObject.IsObjectPropertyInstantiated(expression))
    {
        dirty  = dirty || EnsureCollectionLoaded(clientObject, expression);
    }
}

if (dirty)
{
    clientObject.Context.ExecuteQueryRetry();
}

Using PnP
web.EnsureProperty(w => w.ServerRelativeUrl);

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("Rencore.Analyzers.Assemblies.Rules.PnP.PnPBestPracticesGroup", "SPC029016:UseEnsureProperty", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.