How to get where clause to insert or update in Linq to Sql?

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

        // Do some stuff in the transaction

        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] - , , , , ?

, ...

+3
3

TransactionScope , . .

, , , null ( ), . - , , .

, , . Linq to SQL - , , SQL; , -, , , L2S .

+1

(.. ), UNIQUE .

LINQ-to-SQL, TransactionScope ( SqlTransaction ) . INSERT.

, , , ; , ( ) ?

+1

, LINQ-to-SQL, Any() SingleOrDefault():

using (TransactionScope scope = new TransactionScope())
{
    if (!Context.MyTables.Any(t => t.Value == in.Value))
    {
        MyLinqModels.MyTable t = new MyLinqModels.MyTable()
        {
           Name = in.Name,
           Value = in.Value
        };

        // Do some stuff in the transaction

        scope.Complete();
    }
}

, Any() EXISTS SQL, .

, , - datacontext.

+1
source

Source: https://habr.com/ru/post/1741818/


All Articles