16

i need to do something like this on a transaction context

using(var context = new Ctx())
{

using (TransactionScope tran = new TransactionScope())
{
    decimal debit = 10M;
    int id = 1;

    var data = context.Cashier
        .Where(w => w.ID == id)
        .Select(s => new{ s.Money })
        .Single();


    Cashier cashier = new Cashier(){ ID = id };
    context.Cashier.Attach(cashier);

    cashier.Money = data.Money - debit;
    context.Entry(cashier).Property(p => p.Money ).IsModified = true;

    context.SaveChanges(SaveOptions.None);
    tran.Complete();
}
}

I'm running sql profiler but can't see begin tran, is that block of code correct? Am I missing something?

Alexandre
  • 7,004
  • 5
  • 54
  • 72
  • 2
    Possibly you have then filtered out? You might also try having the ctx creation inside the transaction, just to see I that changes anything. – Marc Gravell Jul 09 '11 at 14:50
  • Why are you using transaction scope for this block of code? `SaveChanges` uses transaction internally if you do not define it so unless you are using multiple transactional resources or calling `SaveChanges` multiple times you do not need it. – Ladislav Mrnka Jul 09 '11 at 15:17
  • Ladislav, it's to prevent wrong data, someone else can modify the cashier money on another methods, if it's not on transaction, this info will be wrong – Alexandre Jul 09 '11 at 15:34
  • @Alexandre: @Ladislav is correct; the `SaveChanges` function always uses a transaction when saving. Unless you are calling `SaveChanges` multiple times (or doing other database manipulation within this block of code), there's no need for another transaction. – Adam Robinson Jul 09 '11 at 15:58
  • 1
    I understand that Adam, but the begin tran of entity framework occures only when calls SaveChanges, I need the transaction before this, more specifically on: context.Cashier .Where(w => w.ID == id) .Select(s => new{ s.Money }) .Single(); – Alexandre Jul 09 '11 at 16:19

1 Answers1

25

Like @Marc said in his comment, the messages are probably being filtered out. You would only be picking up T-SQL transaction messages in the default profile, not transaction messages that are sent using the API directly (as TransactionScope does).

In SQL Server Profiler, go to the trace event selection and check the "Show All Events" checkbox. Down at the bottom is a "Transactions" category, and it should give you what you need. Specifically, the events starting with TM:.

Adam Robinson
  • 182,639
  • 35
  • 285
  • 343