Im trying to make a generic Find method with DapperExtensions
This is my method
public IEnumerable<T> Find(Expression<Func<T, object>> expression)
{
using (IDbConnection cn = GetCn())
{
cn.Open();
var predicate = Predicates.Field<T>(expression, Operator.Eq, true);
return cn.GetList<T>(predicate);
}
}
But i get System.NullReferenceException
on this row var predicate = Predicates.Field<T>(expression, Operator.Eq, true);
This is from the DapperExtensions help documentation But I try convert this to a Generic method.
using (SqlConnection cn = new SqlConnection(_connectionString))
{
cn.Open();
var predicate = Predicates.Field<Person>(f => f.Active, Operator.Eq, true);
IEnumerable<Person> list = cn.GetList<Person>(predicate);
cn.Close();
}
I haven't repro'd, but it looks like the issue is, in part, that you are making the expression more complex than the example. As a suggestion, try:
public IEnumerable<T> Find<TValue>(Expression<Func<T, TValue>> expression,
TValue value)
{
using (IDbConnection cn = GetCn())
{
cn.Open();
var predicate = Predicates.Field<T>(expression, Operator.Eq, value);
return cn.GetList<T>(predicate);
}
}
and:
var data = Find(p => p.MarketId, marketId);
This is completely untested, based just on your comments and the example.
If your code-base doesn't make that practical, then I would suggest just try it with the above to see if that works, because there are ways of pulling apart an expression to extract those pieces. But it isn't worth giving an example of that until we know whether the above works.