如果在sql中存在语句到linq

Kem*_*min 28 sql linq sql-server

以下陈述的linq等价物是什么?

IF NOT EXISTS(SELECT UserName FROM Users WHERE UserName='michael')
BEGIN
INSERT INTO Users (UserName) values ('michael');
END
Run Code Online (Sandbox Code Playgroud)

你也可以建议任何sql-to-linq转换器?我目前正在使用LINQPad,它在编写linq代码方面做得很好,你也可以看到生成的sql代码,但是当我点击小linq符号时,什么也没有显示.

tva*_*son 42

由于LINQ语法和扩展方法不支持插入,因此无法在LINQ2SQL中使用单个语句来完成.以下(假设一个名为datacontext db)应该可以解决问题.

 if (!db.Users.Any( u => u.UserName == "michael" ))
 {
      db.Users.InsertOnSubmit( new User { UserName = "michael" } );
      db.SubmitChanges();
 }
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 6

实现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();
  }
Run Code Online (Sandbox Code Playgroud)

然后将使用扩展方法:

  bool exists = dataContext.Widgets.Exists(a => a.Name == "Premier Widget");
Run Code Online (Sandbox Code Playgroud)

虽然.Where().Any()组合足够有效,但它确实有助于代码表示的逻辑流程.