/CommonDataServiceDynamic

Extending the CDS API to enable dynamic queries.

Primary LanguageC#

CommonDataServiceDynamic

this is a console app which demonstrates extending the CDS API to enable dynamic queries. It extends the .Where method to accept strings as criteria and uses the DynamicExpression class of the Linq Dynamic Query Library to parse strings into valid lambda expressions.

1) Install the library:

You can install it via NuGet with this command in the Nuget Package Manager:

Install-Package System.Linq.Dynamic

2) Then add this Extension method:

using System;

using Microsoft.CommonDataService.Builders;
using Microsoft.CommonDataService.Entities;

namespace Microsoft.CommonDataService
{
    public static class MyBuilders
    {
        public static WhereClauseBuilder<TEntity> Where<TEntity>(this FromClauseBuilder<TEntity> entitySet, string predicate) where TEntity : RelationalEntity//, new()
        {
            return entitySet.Where(WhereExpression<TEntity>(predicate));
        }
        public static System.Linq.Expressions.Expression<Func<T,bool>> WhereExpression<T>(string predicate, params object[] values)
        {
            return System.Linq.Dynamic.DynamicExpression.ParseLambda<T, bool>(predicate, values);
        }
    }
}

3) Usage:

var query = client.GetRelationalEntitySet<ProductCategory>()
        .CreateQueryBuilder()
        //instead of:
        //.Where(pc => pc.Name == "Surface" || pc.Name == "Phone")
        //this:
        .Where("Name = \"Surface\" OR Name = \"Phone\"")
        .Project(pc => pc.SelectField(f => f["CategoryId"]).SelectField(f => f["Name"]));

More Info:

Expression Language