Domanda

I am coding with the class Transaction for .NET and in this specific method I only wish to reinstantiate the Transaction instance if it is not instantiated already. Below is an example done together with some Entity Framework methods.

if (Transaction.Current != null)
{
    using (var transaction = CreateTransaction())
    {
        _dbSet.Attach(item);
        _dbSet.Remove(item);
        _context.SaveChanges();
        transaction.Complete();
    }
}
else
{
    _dbSet.Attach(item);
    _dbSet.Remove(item);
    _context.SaveChanges();
}

I was wondering if there is a smarter way to only use the using-line if the condition above holds. I do not like repeating the same code twice.

È stato utile?

Soluzione

Technically speaking, you could write something like this (because if transaction is null, no auto-dispose will happen as the result of using, see http://msdn.microsoft.com/en-us//library/yh598w02.aspx):

using (var transaction = Transaction.Current == null ? CreateTransaction() : null)
{
    _dbSet.Attach(item);
    _dbSet.Remove(item);
    _context.SaveChanges();
    if(transaction != null)
        transaction.Complete();
}

(I'm not sure about the check. In the original code Transaction.Current != null, however Transaction.Current == null looks more logical.)

But I would consider just grouping

_dbSet.Attach(item);
_dbSet.Remove(item);
_context.SaveChanges();

into a separate function.

Altri suggerimenti

Why not just create a new transaction scope that's within the existing one if one already exists?

But the best thing to do would likely just return a dummy IDisposable if a new transaction doesn't make sense.

// Check if a transaction already exists. if one doesn't create one for
// the purpose of the following changes
Transaction transaction = Transaction.Current == null
  ? CreateTransaction()
  : null;

// changes
_dbSet.Attach(item);
_dbSet.Remove(item);
_context.SaveChanges();

// if we did end up creating one, let's clean up after it.
if (transaction != null)
{
    transaction.Complete();
    transaction.Dispose();
}

Something like that perhaps? (Though this may be a better question for CodeReview)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top