Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert from Expression< Func< Entity, bool> > to Func< Entity, bool>

Tags:

c#

linq

I have this function in my code:

public virtual bool Exists<ENTITY>(Expression<Func<ENTITY, bool>> expr)
{
    return this._dbSet.Count(expr) > 0;
}

I get the error

Cannot convert System.Linq.Expressions.Expression< System.Func< ENTITY, bool>> to System.Func< ENTITY, bool>

now if I change function to this:

public virtual bool Exists<ENTITY>(Expression<Func<ENTITY, bool>> expr)
{
    var tmp = expr.Compile();
    return this._dbSet.Count(tmp) > 0;
}

I get another error:

Cannot convert System.Func< ENTITY, bool> to System.Linq.Expressions.Expression< System.Func< ENTITY, bool> >

What am I doing wrong or is the compiler got crazy? Im using VS2017 C# 7.1

like image 218
Simple Fellow Avatar asked May 08 '26 03:05

Simple Fellow


1 Answers

Assuming that you want to count the entities in _dbSet that fulfill the predicate - in order to check if there is any element at all, after compiling the expression tree,

var tmp = expr.Compile();

you should add this: return this._dbSet.Where(entity => tmp(entity).Count() > 0;

Update

As already nvoigt has pointed out in his answer, it would be more logical to use the Any method:

return this._dbSet.Any(entity => tmp(entity));
like image 160
Christos Avatar answered May 09 '26 17:05

Christos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!