Метод расширения, который реализует решение tvanfosson:
/// <summary>
/// Method that provides the T-SQL EXISTS call for any IQueryable (thus extending Linq).
/// </summary>
/// <remarks>Returns whether or not the predicate conditions exists at least one time.</remarks>
public static bool Exists<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
return source.Where(predicate).Any();
}
/// <summary>
/// Method that provides the T-SQL EXISTS call for any IQueryable (thus extending Linq).
/// </summary>
/// <remarks>Returns whether or not the predicate conditions exists at least one time.</remarks>
public static bool Exists<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int, bool>> predicate)
{
return source.Where(predicate).Any();
}
Тогда будет использован метод расширения:
bool exists = dataContext.Widgets.Exists(a => a.Name == "Premier Widget");
Хотя комбинация .Where (). Any () работает достаточно, она, безусловно, помогает логическому потоку представления кода.