Constructing dynamic LINQ expressions is a pretty niche requirement, however, if you’re in the market for it you will likely want to extend some its expressions to fit your needs. Below I will demonstrate how to extend Microsoft’s .NET 4.0 implementation of System.Linq.Dynamic.
The first step is to create a class and replace it with the following:
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Linq.Expressions;
using
System.Web;
namespace
System.Linq.Dynamic
{
public
static
class
DynamicQueryable
{
}
}
Next we are going to implement a FirstOrDefault() extension. Add the following to your new class:
public
static
object
FirstOrDefault(
this
IQueryable source)
{
if
(source ==
null
)
throw
new
ArgumentNullException(
"source"
);
return
source.Provider.Execute(
Expression.Call(
typeof
(Queryable),
"FirstOrDefault "
,
new
Type[] { source.ElementType },
source.Expression));
}
Now you can implement it on your IQueryable to return a single dynamic object.
//In this case context is the DBContext and sqlQuery is a string builder that built our dynamic select
var results = context.Set<YourEntityName>()
.Where(a => a.Something == "Something")
.Select(sqlQuery.ToString());
var item = results.FirstOrDefault();
We can do something similar to convert our Queryable to a List<dynamic> or IEnumerable<dynamic> in order to actually execute our dynamic query and bring it into memory:
public
static
IEnumerable<dynamic> AsEnumerable(
this
IQueryable source)
{
if
(source ==
null
)
throw
new
ArgumentNullException(
"source"
);
foreach
(var item
in
source)
{
yield
return
item;
}
}
public
static
List<dynamic> ToDynamicList(
this
IQueryable source)
{
if
(source ==
null
)
throw
new
ArgumentNullException(
"source"
);
var items =
new
List<dynamic>();
foreach
(var item
in
source)
{
items.Add(item);
}
return
items;
}
These extension methods, along with others you can implement, make working with dynamic linq much easier and more inline with what most of us are comfortable working with. Enjoy.
The post Extending dynamic LINQ queries with popular expressions appeared first on Falafel Software Blog.