Search code examples
c#entity-frameworklinqdbcontextentity-sql

How to write Dynamic LINQ queries using DBContext in C#


I am modifying my project to use DBContext instead of ObjectContext. My existing code

var query = context.Vehicles.OrderBy("it.VehicleType.VehicleTypeID").
            GroupBy("it.VehicleType.VehicleTypeID", "Min(it.ODO_Reading) AS MinRunVehicle, it.VehicleType.VehicleTypeID");

The above code is written using ObjectContext. After changing my project to inherit from DBContext I am getting the below error

    Error   89  The type arguments for method 'System.Linq.Queryable.OrderBy<TSource,TKey>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource,TKey>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I want to know how to specify dynamic Linq query in DBContext. Can somebody help.


Solution

  • The first example uses eSQL, not some type of dynamic LINQ.

    DbContext doesn't allow you to perform eSQL queries directly, but you can get access to the underlying ObjectContext and use it as before:

    var query = ((IObjectContextAdapter)context).ObjectContext
                                                .CreateQuery<Vehicle>("<ESQL Query>")