Linq使用事务

public void AddBook(int userId, acb_Book newBook, bool defaultBook, int startMoney)
{
    
using (AccountBookDataContext ctx = new AccountBookDataContext())
    {
        
int haveBookCount = ctx.acb_Book.Count(b => b.CreateAccountId == userId);
        
if (haveBookCount < 5)
        {
            ctx.Connection.Open();
            ctx.Transaction 
= ctx.Connection.BeginTransaction(IsolationLevel.Serializable);
            
try
            {
                ctx.acb_Book.InsertOnSubmit(newBook);
                ctx.SubmitChanges();

                
if (defaultBook)
                {
                    newBook.acb_UserInfo.DefaultBookId 
= newBook.Id;
                }
                ctx.SubmitChanges();

                
if (startMoney != 0)
                {
                    acb_BookItem item 
= new acb_BookItem();
                    item.AccountDateTime 
= DateTime.Now;
                    item.CreateAccountId 
= userId;
                    item.CreaetDateTime 
= DateTime.Now;
                    item.Name 
= "我的启动资金";
                    item.Money 
= startMoney;
                    item.acb_SystemClass 
= (from sc in ctx.acb_SystemClass where sc.Name == "暂无分类" select sc).Single();
                    newBook.acb_BookItem.Add(item);
                }
                ctx.SubmitChanges();

                ctx.Transaction.Commit();
            }
            
catch (Exception ex)
            {
                ctx.Transaction.Rollback();
                
throw ex;
            }
            
finally
            {
                ctx.Connection.Close();
                ctx.Transaction 
= null;
            }
        }
        
else
        {
            
throw new Exception("每个用户只能创建5个帐本");
        }
    }
}


posted @ 2008-08-12 14:44  王其荣的博客  阅读(554)  评论(0编辑  收藏  举报