Sql – if exists statement in sql to linq


What is the linq equivalent of the following statement ?

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

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.

Best Solution

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.

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