Как использовать транзакции с Платформой Объекта?

Это очень общая функция, которую я написал для генерации случайных уникальных / неповторимых целых чисел для массива. Предположим, что последний последний параметр был истинным в этом сценарии для этого ответа.

/* Creates an array of random integers between the range specified 
     len = length of the array you want to generate
     min = min value you require
     max = max value you require
     unique = whether you want unique or not (assume 'true' for this answer)
*/
    function _arrayRandom(len, min, max, unique) {
        var len = (len) ? len : 10,
                min = (min !== undefined) ? min : 1,
                max = (max !== undefined) ? max : 100,
                unique = (unique) ? unique : false,
                toReturn = [], tempObj = {}, i = 0;

        if(unique === true) {
            for(; i < len; i++) {
                var randomInt = Math.floor(Math.random() * ((max - min) + min));
                if(tempObj['key_'+ randomInt] === undefined) {
                    tempObj['key_'+ randomInt] = randomInt;
                    toReturn.push(randomInt);
                } else {
                    i--;
                }
            }
        } else {
            for(; i < len; i++) {
                toReturn.push(Math.floor(Math.random() * ((max - min) + min)));
            }
        }

        return toReturn;
    }

Здесь «tempObj» является очень полезным obj, поскольку каждое генерируемое случайное число будет напрямую проверять этот tempObj, если этот ключ уже существует , если нет, то мы уменьшаем i на единицу, так как нам нужен один дополнительный прогон, так как текущее случайное число уже существует.

В вашем случае запустите следующий

_arrayRandom(8, 1, 100, true);

. Это все.

27
задан pupeno 28 June 2009 в 14:03
поделиться

3 ответа

You can place your code within a Transaction scope

using(TransactionScope scope = new TransactionScope())
{
    // Your code
    scope.Complete(); //  To commit.
}

TransactionScope is in the System.Transactions namespace which is located in the assembly of the same name (which you may need to add manually to your project).

26
ответ дан 28 November 2019 в 04:12
поделиться

ObjectContext имеет свойство подключения, которое вы можете использовать для управления транзакциями.

using (var context = new BlahEntities())
using (var tx = context.BeginTransaction())
{
    // do db stuff here...
    tx.Commit();
}

В случае исключения транзакция будет отменена. Поскольку вызов BeginTransaction () требует открытого соединения, имеет смысл заключить вызов BeginTransaction, возможно, в метод расширения.

public static DbTransaction BeginTransaction(this ObjectContext context)
{
    if (context.Connection.State != ConnectionState.Open)
    {
        context.Connection.Open();
    }
    return context.Connection.BeginTransaction();
}

Один из сценариев, где я считаю, что этот подход может быть полезен для TransactionScope, - это когда вам нужно получить доступ к двум источникам данных и вам нужен только транзакционный контроль над одним из соединений. Я думаю, что в этом случае TransactionScope будет продвигаться к распределенной транзакции, которая может не потребоваться.

55
ответ дан Kim Major 14 October 2019 в 12:31
поделиться

I know that for LINQ to SQL, the data context will create a transaction for SubmitChanges() if there is no existing ambient transaction (TransactionScope is an "ambient" transaction). I haven't seen this documented for LINQ to Entities, but I have seen behavior to suggest that it's true for Entity Framework as well.

So as long as you use one SubmitChanges() (L2SQL) or SaveChanges() (Linq to Entities) for all the related changes, you should be OK without using TransactionScope. You need a TransactionScope when

  1. Saving multiple changes with multiple SubmitChanges/SaveChanges for one transaction.
  2. Updating multiple data sources within one transaction (e.g., Linq and ASP.NET membership SQL provider).
  3. Calling other methods that may do their own updates.

I've had trouble with nested TransactionScopes. They're supposed to work, and simple test cases work, but when I get into production code, the "inner" transaction seems to be the same object as the outer transaction. Symptoms include errors that are either "transaction committed, you can't use this transaction any more" or "this transaction object has already been disposed". The errors occur in the outer transaction after the inner transaction has done its work.

9
ответ дан 28 November 2019 в 04:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: