2010-06-27 28 views
0

我嘗試學習事務範圍。一切看起來不錯。我嘗試控制交易正在運行,我在NAME值中添加了500個字符(通常名稱爲nvarchar(50))。雖然我的formApplication沒有運行(這是正常的),我試圖打開一個表格表是空的。停止運行我的應用表單。我可以看到表格的值。爲什麼?如何學習EF或LINQ to SQL中的事務?

using (var ctx = new DataClassesCallCenterDataContext()) 
{ 
    using (var scope = new TransactionScope()) 
    { 
     var test = 
      from c in ctx.sp_CallCenterAnketEntity() 
      select c; 

     int? ID = test.ToList()[0].ID; 

     var question = new QuestionsYesNo(); 
     question.Question = "Test3?"; 
     question.Date = DateTime.Now; 

     ctx.QuestionsYesNos.InsertOnSubmit(question); 
     ctx.SubmitChanges(); 

     Rehber rehber = (
      from r in ctx.Rehbers 
      where r.ID == ID 
      select r).First(); 

     rehber.Name = 
      @"SQL Server 2005'i bir [many more characters] izleyin."; 

     ctx.SubmitChanges(); 

     scope.Complete(); 
    } 
} 

我嘗試打開QuestionsYesNo表。我不能在我的應用程序運行?

+2

你需要接受更多的答案 – 2010-06-27 12:20:31

+0

而你需要改一下你的問題。很難說出這裏要問什麼。 – Steven 2010-06-27 12:41:54

回答

1

只是一點點重寫告訴你如何代碼可能看起來像:

// use nested using block to decrease the indent 
using (var ctx = new DataClassesCallCenterDataContext()) 
using (var scope = new TransactionScope()) 
{ 
    var test = 
     from c in ctx.sp_CallCenterAnketEntity() 
     select c; 

    // if you're sure that query result will have at least one record. 
    // else an exception will occur. use FirstOrDefault() if not sure. 
    // and why int? - is it the type of ID. Isn't int the type? 
    int? ID = test.First().ID; 

    // here you can use object initializer 
    var question = new QuestionsYesNo 
    { 
     Question = "Test3?", 
     Date = DateTime.Now 
    }; 

    ctx.QuestionsYesNos.InsertOnSubmit(question); 
    ctx.SubmitChanges(); 

    Rehber rehber = (
     from r in ctx.Rehbers 
     where r.ID == ID 
     select r).First(); // again about being sure and FirstOrDefault 

    rehber.Name = @"SQL Server 2005'i bir [many more characters] izleyin."; 

    ctx.SubmitChanges();  
    scope.Complete(); 
}