Skip to content

Get expression tree from query string

Maxim edited this page Nov 14, 2019 · 8 revisions

Data source data context

IEdmModel edmModel = new OrderDataAdapter(allowCache: true,useRelationalNulls: true).BuildEdmModel();

var optionsBuilder = new DbContextOptionsBuilder<OrderContext>();
optionsBuilder = optionsBuilder.UseSqlServer(@"Server=.\sqlexpress;Initial Catalog=OdataToEntity;Trusted_Connection=Yes");
var orderContext = new OrderContext(optionsBuilder.Options);

await Execute(edmModel, orderContext);


static async Task Execute(IEdmModel edmModel, OrderContext orderContext)
{
    var queryExression = new OeQueryExpression(edmModel, "Customers?$filter=Address gt 'London'&$expand=Orders&$orderby=Country,Id");
    Expression expression = queryExression.GetExpression(orderContext);
    //$expand=Orders translate to Tuple<Customer, Order>
    IQueryable<Tuple<Customer, Order>> query = orderContext.Customers.AsQueryable().Provider.CreateQuery<Tuple<Customer, Order>>(expression);
    //translate Tuple<Customer, Order> to Customer and set navigation property Orders
    List<Customer> result = await queryExression.Materialize<Customer>(query).ToListAsync();
}

Data source IQueryable, cannot use $expand

IEdmModel edmModel = new OrderDataAdapter(allowCache: true,useRelationalNulls: true).BuildEdmModel();

var optionsBuilder = new DbContextOptionsBuilder<OrderContext>();
optionsBuilder = optionsBuilder.UseSqlServer(@"Server=.\sqlexpress;Initial Catalog=OdataToEntity;Trusted_Connection=Yes");
var orderContext = new OrderContext(optionsBuilder.Options);

await Execute(edmModel, orderContext.Customers);


static async Task Execute(IEdmModel edmModel, IQueryable<Customer> customers)
{
    Expression expression = OeQueryExpression.GetExpression(edmModel, "Customers?$filter=Address gt 'London'&$orderby=Country,Id", customers);
    List<Customer> result = await customers.AsQueryable().Provider.CreateQuery<Customer>(expression).ToListAsync();
}