If you have to use just DataContext
, then you can build the expression manually. In this case I'm using a selector expression, but reflection on a property-name (i.e. "Name") would do just as well:
static void Main()
{
string knownName;
using (DataClasses1DataContext ctx = new DataClasses1DataContext())
{
knownName = ctx.Customers.First().CompanyName;
}
using (DataContext ctx = new DataClasses1DataContext())
{
Console.WriteLine(ctx.Any<Customer, string>(
cust => cust.CompanyName, "none-such"));
Console.WriteLine(ctx.Any<Customer, string>(
cust => cust.CompanyName, knownName));
}
}
static bool Any<TEntity, TValue>(
this DataContext ctx,
Expression<Func<TEntity, TValue>> selector,
TValue value)
where TEntity : class
{
var lambda =
Expression.Lambda<Func<TEntity, bool>>(
Expression.Equal(
selector.Body,
Expression.Constant(value, typeof(TValue))),
selector.Parameters);
return ctx.GetTable<TEntity>().Any(lambda);
}
The string-based approach would be:
using (DataContext ctx = new DataClasses1DataContext())
{
Console.WriteLine(ctx.Any<Customer, string>("CompanyName", "none-such"));
Console.WriteLine(ctx.Any<Customer, string>("CompanyName", knownName));
}
...
static bool Any<TEntity, TValue>(
this DataContext ctx,
string propertyOrFieldName,
TValue value)
where TEntity : class
{
var param = Expression.Parameter(typeof(TEntity), "row");
var lambda =
Expression.Lambda<Func<TEntity, bool>>(
Expression.Equal(
Expression.PropertyOrField(param, propertyOrFieldName),
Expression.Constant(value, typeof(TValue))),
param);
return ctx.GetTable<TEntity>().Any(lambda);
}