Using Expression Class With LINQ Queries - c#

I was wondering if there's a way to use Expression class for custom queries with LINQ queries such as this
Expression<Func<TEntity, bool>> expression = (x) => x.Id = 1
var items = from item in context.TEntity
where expression
select item
I know there's a way to do this using LINQ function as the Where function takes an expression as a parameter but I really need to do this using LINQ queries
note: the code above is just an example to make you get around what I'm trying to do it's not an actual working code
note 2: I need this to work with Entity Framework

Unfortunately, Entity Framework does not natively support this type of expression projection, which is why a common attempt such as where expression.Compile().Invoke(item); will throw an exception at runtime.
However, if you use the LinqKit library (which utilizes the Expression Visitor) and call .AsExpandable() on the entity set, you can then invoke your expression dynamically:
Expression<Func<TEntity, bool>> expression = x => x.Id == 1;
var items = from item in context.Set<TEntity>.AsExpandable()
where expression.Invoke(item)
select item;

This works, at least on EF Core (I have just tested it). Don't have any EF6 project handy where I could test.
Expression<Func<TEntity, bool>> expression = (x) => x.Id = 1
var items = from item in context.TEntity
where expression.Compile()(item);
select item
Update: I just made a simple test project on EF6 and it does not work there, since it doesn't recognize the expression invocation

Related

How to invoke lambda expression when calling sql query?

I need to create a generic method (ContainsLambda) that takes collection and a lambda expression (a single property) and would check if the given property contains values in the given collection.
Here is my method
public static TModel[] ContainsLambda<TModel, TKey>(IEnumerable<TKey> keys, Func<TModel, TKey> property)
{
DbSet<TModel> repository = DbContext.Set<TModel>();
return repository.Where(x => keys.Contains(property.Invoke(x)))
.ToArray();
}
Then I would call it using something like this ContainsLambda<Customer, int>(new List<int> {10, 20, 30}, p => p.Age)
The above code throws the following runtime error.
LINQ to Entities does not recognize the method 'Int32
Invoke(Customer)' method, and this method cannot be translated into a
store expression.
How can I call .Invoke() on a lambda that would be used in LINQ which would then be translated into SQL expression?
Try making your repository an enumerable. This bypasses Linq to Entities, and causes your code to run in Linq to Objects.
return repository.AsEnumerable()
.Where(x => keys.Contains(property.Invoke(x)))
.ToArray();
If you don't want all of the records in your repository to travel across the wire (i.e. you need the filtering to run on the server), you will have to write a custom SQL query to retrieve the data.

Entity Framework Core, emitting/generating expression in select

I'm using Entity Framework Core in .Net Core 2.2, with the recently released Oracle.EntityFrameworkCore library.
I'd like to be able to generate a query like this...
select nvl(nullablecolumn, 'N') from table;
I think I'm right in saying that I can't do this, at least not out of the box... I can however do something similar, using something like this (but then if I end up writing this, why not write actual SQL and skip Entity Framework???)...
from row in table
select new { somedata = row.nullablecolumn ?? "N" };
The above linq query gets me the same sort of answer as I'm after... question is, can I do some expression tree magic to get the same result?
For example, this question looks like it generates an expression tree for a "like" query, so how would I generate an expression tree (or modify the existing expression tree) to make the select side of the statement emit nvl()?
This would be useful where you have Entity Framework Value Conversions...
Bonus points (if I could give bonus points) if you can give me a clue on how to create an expression tree to manipulate the where side of the query... AutoMapper manages this somehow with "Projections"?
Any thoughts/pointers would be greatly appreciated...
To translate your own method invocation to proper SQL function you can use HasDbFunction from docs.
You have to define own static method as
public static class OracleDbFunction
{
public static string Nvl(string string1, string replace_with) => throw new NotImplementedException(); // You can provide matching in-memory implementation for client-side evaluation of query if needed
}
register it in your DbContext
protected overridevoid OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDbFunction(typeof(OracleDbFunction).GetMethod(nameof(OracleDbFunctionExtensions.Nvl, builder =>
{
builder.HasName("nvl");
});
}
and use it in your Where expression as
.Where(i => OracleDbFunction.Nvl(i.nullablecolumn, "N") == "N")
You can also use attribute DbFunctionAttribute on OracleDbFunctionExtensions.Nvl to avoid registering it in OnModelCreating

Entity Framework Lambda predicate stored in var with association

I have a generic repository using EF6. The issue has to do with association properties requiring an "Include" even though it shouldn't. The following works:
IQueryable<User> dbQuery = _db.Set<User>();
return dbQuery.Where(x => x.Child.Name == "Foo").ToList();
However, the following does not work:
Func<User, bool> filter = x => x.Child.Name == "Foo";
IQueryable<User> dbQuery = _db.Set<User>();
return dbQuery.Where(filter).ToList();
It throws an "Object Reference not set..." exception on Child.
The following resolves it:
Func<User, bool> filter = x => x.Child.Name == "Foo";
IQueryable<User> dbQuery = _db.Set<User>();
dbQuery = dbQuery.Include(x => x.Child);
return dbQuery.Where(filter).ToList();
I don't understand why this is necessary though. Anyone know a way to resolve this without using the "Include"?
You are should use Expression to let EF provider parse your query.
Change the Func<User, bool> to Expression<Func<User, bool>>
The first snippet is providing an Expression to Where, which is being translated into SQL, and is doing the entire operation in the database. The latter two are passing a compiled method to Where, which it can't translate into SQL, which means that the entire database table is being pulled down into memory, and the entire operation is run in your application. When you pull down the whole table it doesn't pull down related records unless you Include them.
The solution is not to pull down both the entire table and also all of the data from all of the related records; the solution is to do the filtering in the database rather than in your application.

Passing an expression from a LINQ Queryable

I have a Service Repository pattern built on top of Entity Framework.
The service has methods such as Find(IQuery query) that return IEnumerable.
The IQuery object is our own query object type where we convert strings to an IQueryable expression that the repository, which exposes IQueryable, can use.
What I'd like to do is be able to write a queryable on the client side and pass that over the service so that we can take advantage of the static typing and linq style queries instead of building our own query object in formation.
In other words I want to be able to do something like:
var query = new List<Type>().Where(x => x.Property == "argument").AsQueryable();
service.find(query);
Then I would pass the queryable or the expression it creates to my repository and work like that.
Is this sort of thing possible, or would I have to build the expression from scratch? It seems like this should be possible, but I really don't know where to begin or see examples of how to share an expression like this.
If you call AsQueryable() on an IEnumerable that doesn't already implement IQueryable, then that whole enumerable is just stuffed into a ConstantExpression, and any previous LINQ operations are not expressed as expression trees.
If you call AsQueryable() right on the source, then the LINQ operations will return an IQueryable with the proper query expression tree:
var query = new List<Type>().AsQueryable().Where(x => x.Property == "argument");

Dynamic Linq gives error in combination with EntityFramework

We use Entity Framework, and we need some runtime build queries on our objects. Building expression trees from scratch seems like a lot of work, so we want to use "System.Linq.Dynamic"
Working through the samples I got this to work:
dbModel.As.Where("AStuff.Contains(#0) OR AStuff.Contains(#1)","ac","bc")
But if I try to build the expressions seperately like this:
Expression<Func<A, bool>> predicateA =
DynamicExpression.ParseLambda<A, bool>(
"AStuff.Contains(#0)",
"ac"
);
Expression<Func<A,bool>> predicateB =
DynamicExpression.ParseLambda<A, bool>(
"AStuff.Contains(#0)",
"bc"
);
dbModel.As.Where("#0(it) OR #1(it)", predicateA, predicateB);
it explodes with an exception:
NotSupportedException>>The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.
It may be possible to build the entire query in the first form, but the later would be more useful in our scenario. Is there a way to make that work?
Just use Predicate Builder to join (Or/And) multiple predicates.

Categories