I am trying to convert the following stored process into a LinqToSql call (this is a simplified version of SQL):
INSERT INTO [MyTable]
([Name], [Value])
SELECT
@name, @value
WHERE
NOT EXISTS(SELECT [Value] FROM [MyTable] WHERE [Value] = @value)
The database has no restriction on the field that is checked, so in this particular case, the check must be performed manually. There are also many elements that are constantly inserted, so I need to make sure that when this particular insert occurs, there is no cheating on the value field. My first guess is this:
using (TransactionScope scope = new TransactionScope())
{
if (Context.MyTables.SingleOrDefault(t => t.Value == in.Value) != null)
{
MyLinqModels.MyTable t = new MyLinqModels.MyTable()
{
Name = in.Name,
Value = in.Value
};
scope.Complete();
}
}
This is the first time I've really come across this scenario, so I want to make sure that I'm going to do it right. Is this right, or can anyone suggest a better way around this without two separate calls?
Edit: I am having an update problem:
UPDATE [AnotherTable]
SET [Code] = @code
WHERE [ID] = @id AND [Code] IS NULL
Linqtosql? , get, , , - [Code] - , , , , ?
, ...