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
You didn't post your full code so I'm guessing here:
You class already is generic with a parameter ENTITY
. So drop the <ENTITY>
of Exists<ENTITY>
because that means your method is generic and different from your class . But it must be the same generic parameter as the class and your DbSet
so just use the class' generic parameter.
class Repository<ENTITY>
{
public virtual bool Exists(Expression<Func<ENTITY, bool>> expr)
{
return this._dbSet.Count(expr) > 0;
}
}
Sidenote: an EXISTS would probably be an .Any()
, not .Count() > 0
.
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.