Próbuję zaktualizować dane podczas ich odczytu z bazy danych, patrz poniżej. Po tym wszystkim dane nie zostały zaktualizowane.Dlaczego nie mogę zaktualizować danych do bazy danych za pomocą LINQ do SQL?
Czy istnieje jakaś składnia transakcji, którą należy podać? (Kiedy debugowania, widzę, że mam prawo rekord pobrana.)
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();
}
Oto moja procedura:
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
I jeśli mogę umieścić wszystkie moje kodu wewnątrz TransactionScope
bloku
using (TransactionScope scope = new TransactionScope())
{
// all the C# code above
scope.Complete();
}
Otrzymam wyjątek "MSDTC na serwerze" localhost-sqlserver2005 "jest niedostępny."
I jeśli tylko umieścić niektóre kodu, nie ma wyjątków, ale dane did`t aktualizowane
using (TransactionScope scope = new TransactionScope())
{
sampleTable1 table1 = context.sampleTable1s.SingleOrDefault(t=> t.id = c.ID);
table1.isRead = 1;
context.SubmitChanges();
scope.Complete();
}
Dzięki.
noloack? zastanawiasz się, czy to jest literówka w pytaniu, czy złamany SPROC –
Aby potwierdzić - czym jest 'table1.isRead' * przed * tym? Obowiązuje tylko faktyczne * zmiany *, więc jeśli było 1 przed, bez zmian. Czy próbowałeś przechwycić log ('context.Log = Console.Out;'), aby zobaczyć, co przesyła? (podobna alternatywa - użyj programu profilującego SQL) –
@Marc, jest to literówka..sprzęt – jojo