如果在 sql 到 linq 中存在语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/476214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:51:44  来源:igfitidea点击:

if exists statement in sql to linq

sqlsql-serverlinq

提问by Subliminal Hash

What is the linq equivalent of the following statement ?

以下语句的 linq 等效项是什么?

IF NOT EXISTS(SELECT UserName FROM Users WHERE UserName='michael')
BEGIN
INSERT INTO Users (UserName) values ('michael');
END

also can you suggest any sql-to-linq converters? I am currently using LINQPad which does a great job in terms of writing linq code where you can also see the generated sql code however when I click the little linq sign, nothing is displayed.

你也可以推荐任何 sql-to-linq 转换器吗?我目前正在使用 LINQPad,它在编写 linq 代码方面做得很好,您还可以在其中看到生成的 sql 代码,但是当我单击小 linq 标志时,没有显示任何内容。

回答by tvanfosson

It can't be done in LINQ2SQL with a single statement as the LINQ syntax and extension methods don't support inserts. The following (assuming a datacontext named db) should do the trick.

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

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

回答by Michael

Extension method that implements tvanfosson's solution:

实现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();
  }

The extension method would then be used:

然后将使用扩展方法:

  bool exists = dataContext.Widgets.Exists(a => a.Name == "Premier Widget");

Although the .Where().Any() combination works sufficiently, it does certainly help the logic flow of the code presentation.

尽管 .Where().Any() 组合足够有效,但它确实有助于代码呈现的逻辑流程。

回答by Brian Wells

Put the Exists code in a static class. e.g. add a class to your project w/ something like:

将 Exists 代码放在静态类中。例如,将一个类添加到您的项目中,例如:

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();
        }


    }
}

Don't forget to add the namespace of this class to any other class using it. ;P

不要忘记将此类的命名空间添加到使用它的任何其他类。;P