If существует в sql для linq
Что такое эквивалент linq следующего оператора?
IF NOT EXISTS(SELECT UserName FROM Users WHERE UserName='michael')
BEGIN
INSERT INTO Users (UserName) values ('michael');
END
также можете предложить любые конвертеры sql-to-linq? В настоящее время я использую LINQPad, который отлично справляется с написанием кода linq, где вы также можете увидеть сгенерированный код sql, однако, когда я нажимаю маленький знак linq, ничего не отображается.
Ответы
Ответ 1
Это невозможно сделать в LINQ2SQL с помощью одного оператора, поскольку методы синтаксиса и расширения LINQ не поддерживают вставки. Следующее (при использовании datacontext с именем db
) должно выполнить трюк.
if (!db.Users.Any( u => u.UserName == "michael" ))
{
db.Users.InsertOnSubmit( new User { UserName = "michael" } );
db.SubmitChanges();
}
Ответ 2
Метод расширения, реализующий решение 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() работает достаточно, она, безусловно, помогает логическому потоку представления кода.
Ответ 3
Поместите код Exists в статический класс. например добавьте класс в свой проект w/something like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace company.project
{
static class LinqExtensions
{
/// <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();
}
}
}
Не забудьте добавить пространство имен этого класса в любой другой класс, используя его.; Р