以下陈述的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符号时,什么也没有显示。
答案 0 :(得分:42)
由于LINQ语法和扩展方法不支持插入,因此无法在LINQ2SQL中使用单个语句来完成。以下(假设名为db
的datacontext)应该可以解决问题。
if (!db.Users.Any( u => u.UserName == "michael" ))
{
db.Users.InsertOnSubmit( new User { UserName = "michael" } );
db.SubmitChanges();
}
答案 1 :(得分: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();
}
然后将使用扩展方法:
bool exists = dataContext.Widgets.Exists(a => a.Name == "Premier Widget");
虽然.Where()。Any()组合足够有效,但它确实有助于代码表示的逻辑流程。
答案 2 :(得分:2)
将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();
}
}
}
不要忘记将此类的命名空间添加到使用它的任何其他类。 ; P