2010-09-16 19 views
6

我正試圖在數據庫中讀取數據時更新數據,請參閱下文。 但整個事情完成後,數據沒有得到更新。爲什麼我無法使用LINQ to SQL將數據更新到數據庫中?

是否有我需要指定的任何事務語法? (當我調試,我可以看到我有權利記錄中檢索。)

using (conn = new SqlConnection(MyConnectionString)) 
       using (SqlCommand cmd = new SqlCommand("dbo.MyProcedure", conn)) 
       { 
        cmd.CommandType = CommandType.StoredProcedure; 
        cmd.Parameters.AddWithValue("@Count", count); 
        conn.Open(); 
        using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) 
        { 
         while (reader.Read()) 
         { 
          // wrapper object, not related to database 
          SampleModel c = new SampleModel(); 
          c.ID= (string)reader["ID"]; 
          c.Name = (string)reader["Name"]; 
          c.Type = (int)reader["Type"]; 

          // modeList will return to outside, not related to database 
          modelList.Add(c); 

          sampleTable1 table1 = context.sampleTable1s.SingleOrDefault(t=> t.id = c.ID); 

          // try to update the "isRead", but it doesn`t work....!!! 
          // about the datatype, in the data base, it is "smallInt" 
          // in linq to sql, it is "short?" 
          // PS Default value all should be 0 
          table1.isRead = 1; 
          context.SubmitChanges(); <--- here, it doesn`t do the job // context is new from Linq to SQL 
         } 
        } 
        conn.Close(); 
       } 

這裏是我的方法:

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
CREATE PROCEDURE MyProcedure  
    @Count int = 100 
AS 
BEGIN 

    SELECT TOP (@Count) 
     t1.id AS ID, 
     t1.name AS Name, 
     t2.type AS TYPE  
    FROM sampleTable1 as t1 with (nolock), 
     sampleTable2 as t2 with (nolock)   
    WHERE (t1.t2Id = t2.Id)  
ORDER BY t1.name asc 

END 
GO 

如果我把我所有的代碼中TransactionScope

using (TransactionScope scope = new TransactionScope()) 
{ 
    // all the C# code above 
    scope.Complete(); 
} 

我將得到一個異常「服務器'localhost-sqlserver2005'上的MSDTC不可用。」

如果我只是把一些代碼的,沒有例外,但數據did`t得到更新

using (TransactionScope scope = new TransactionScope()) 
{ 
    sampleTable1 table1 = context.sampleTable1s.SingleOrDefault(t=> t.id = c.ID); 

    table1.isRead = 1; 
    context.SubmitChanges(); 

    scope.Complete(); 
} 

感謝。

+0

noloack?想知道這是否是問題中的拼寫錯誤,或者是SPROC – 2010-09-16 05:19:06

+0

要確認 - 在此之前什麼是table1.isRead * *?它只適用於實際的*變化*,所以如果它是1之前,沒有變化。您是否嘗試捕獲日誌('context.Log = Console.Out;')以查看它提交的內容? (類似的選擇 - 使用SQL分析器) – 2010-09-16 05:21:58

+0

@Marc,它是一個錯字.sorry – jojo 2010-09-16 05:52:42

回答

8

檢查以便在L2S設計器中至少將相關實體類中的一個成員標記爲主鍵成員。如果一個實體沒有任何PK成員,L2S將在提交更新時靜靜地忽略它(默默地拋出,沒有更新的SQL語句生成併發送到數據庫)。

+1

..你是精靈......我忘了在腳本中創建主鍵。讓我試試發生了什麼後,我把小學 – jojo 2010-09-16 07:15:39

+1

它現在正在工作.....- _- !!!! – jojo 2010-09-16 07:19:28

+0

只是附加說明:獲取更新(和刪除)語句的關鍵是如果模型認爲有PK。當然,如果數據庫中有一個PK,但是對於DB表沒有PK的情況,最好是將一個或多個列(唯一標識記錄)標記爲PK成員並且L2S將會很快樂。 – KristoferA 2010-09-16 07:19:38