Querying a SharePoint list via Microsoft.Graph after upgrading to .NET SDK v5
I've just finished upgrading all the project references in a CRM solution I built a while ago, which was using the Microsoft.Graph v4 .NET SDK (via the Microsoft.Graph v4.35.0 NuGet package, to be precise), which meant I took an upgrade to the latest version (v5.37.0 at the time of writing) which comes with some breaking changes. The changelog and upgrade guide is a good starting point but the one bit that took a little bit of jiggling to get working again was retrieving items from a SharePoint list.
The original code looked like this:
public async Task<IEnumerable<Order>> GetOrders() { var client = await GetGraphApiClient(); var queryOptions = new List<QueryOption>() { new QueryOption("expand", "fields(select=*)") }; var list = await client.Sites[SiteId] .Lists[OrdersListId] .Items .Request(queryOptions) .GetAsync(); var items = from item in list select GetFromListItemAdditionalData(item, item.Fields.AdditionalData); return items.ToList(); } public Order GetFromListItemAdditionalData(ListItem item, IDictionary<string, object> additionalData) { var title = additionalData["Title"].AsJsonElement().GetString();
The revised code is:
public async Task<IEnumerable<Order>> GetOrders() { var client = await GetGraphApiClient();
var list = await client.Sites[SiteId] .Lists[OrdersListId] .Items .GetAsync(requestConfiguration => { requestConfiguration.QueryParameters.Expand = ["fields($select=*)"]; });
var items = from item in list.Value select GetFromListItemAdditionalData(item, item.Fields.AdditionalData); return items.ToList(); } public Order GetFromListItemAdditionalData(ListItem item, IDictionary<string, object> additionalData) { var title = additionalData["Title"] as string;
..
..
return new Order(title, ... ...);
}
The bit that took some digging to find the requried tweak was the addition of a "$" prefixing "select" in the expand query definition. The other changes were:
- Changing from using QueryOption to QueryParameters.Expand to pull all the additional list columns (i.e. the user columns in the list like title, order id, order date, etc,..) in the results returned
- Having the LINQ query operate on list.Value instead of list to process all the list items
- No longer needing the call to AsJsonElement to operate on the "AdditionalData" elements
There's nothing particularly complicated, or ground-breaking, there... it did take more searches and digging around than i would like to come up with code that both compiled and worked after upgrading to v5 of the Microsoft.Graph .NET SDK though! Hopefully the note about changing "fields(select=*)" to "fields($select=*)" will help someone out!