Tôi đang cố gắng cập nhật dữ liệu trong khi đọc chúng từ cơ sở dữ liệu, xem bên dưới. Nhưng sau khi kết thúc mọi thứ, dữ liệu không được cập nhật.Tại sao tôi không thể cập nhật dữ liệu vào cơ sở dữ liệu bằng LINQ to SQL?
Có bất kỳ cú pháp giao dịch nào tôi cần chỉ định không? (Khi tôi gỡ lỗi, tôi có thể thấy tôi có kỷ lục ngay lấy.)
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();
}
Dưới đây là thủ tục của tôi:
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
Và nếu tôi đặt tất cả các mã của tôi bên TransactionScope
khối
using (TransactionScope scope = new TransactionScope())
{
// all the C# code above
scope.Complete();
}
Tôi sẽ nhận được ngoại lệ "MSDTC trên máy chủ 'localhost-sqlserver2005' không khả dụng".
Và nếu tôi chỉ đưa một số mã, không có ngoại lệ, nhưng các dữ liệu được cập nhật did`t
using (TransactionScope scope = new TransactionScope())
{
sampleTable1 table1 = context.sampleTable1s.SingleOrDefault(t=> t.id = c.ID);
table1.isRead = 1;
context.SubmitChanges();
scope.Complete();
}
Cảm ơn.
noloack? tự hỏi nếu đó là một lỗi đánh máy trong câu hỏi, hoặc một SPROC –
bị hỏng Để xác nhận - những gì là 'table1.isRead' * trước * điều này? Nó chỉ áp dụng * thay đổi * thực tế, vì vậy nếu nó là 1 trước đó, không thay đổi. Bạn đã thử chụp nhật ký ('context.Log = Console.Out;') để xem nó đang gửi gì chưa? (tương tự thay thế - sử dụng một lược tả SQL) –
@Marc, nó là một lỗi đánh máy .. xin lỗi – jojo