以下陈述的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符号时,什么也没有显示.
由于LINQ语法和扩展方法不支持插入,因此无法在LINQ2SQL中使用单个语句来完成.以下(假设一个名为datacontext db
)应该可以解决问题.
if (!db.Users.Any( u => u.UserName == "michael" )) { db.Users.InsertOnSubmit( new User { UserName = "michael" } ); db.SubmitChanges(); }
实现tvanfosson解决方案的扩展方法:
////// Method that provides the T-SQL EXISTS call for any IQueryable (thus extending Linq). /// ///Returns whether or not the predicate conditions exists at least one time. public static bool Exists(this IQueryable source, Expression > predicate) { return source.Where(predicate).Any(); } /// /// Method that provides the T-SQL EXISTS call for any IQueryable (thus extending Linq). /// ///Returns whether or not the predicate conditions exists at least one time. public static bool Exists(this IQueryable source, Expression > predicate) { return source.Where(predicate).Any(); }
然后将使用扩展方法:
bool exists = dataContext.Widgets.Exists(a => a.Name == "Premier Widget");
虽然.Where().Any()组合足够有效,但它确实有助于代码表示的逻辑流程.