I have a method for updating some tables. For update I need get first of TestProcess
, but I don\'t like that. How can I update TestProcess
without
The code:
TestProcess testprocess = dbcontext.TestProcesses.Attach(new TestProcess { MyID = id });
tp.UpdateID = updateID;
dbcontext.Entry(testprocess).Property(tp => tp.UpdateID).IsModified = true;
dbcontext.Configuration.ValidateOnSaveEnabled = false;
dbcontext.SaveChanges();
The result TSQL:
exec sp_executesql N'UPDATE [dbo].[TestProcesses]
SET [UpdateID] = @0
WHERE ([MyID] = @1)
',N'@0 bigint,@1 bigint',@0=2,@1=1
Note:
The "IsModified = true" line, is needed because when you create the new TestProcess object (only with the MyID property populated) all the other properties has their default values (0, null, etc). If you want to update the DB with a "default value", the change will not be detected by entity framework, and then DB will not be updated.
In example:
testprocess.UpdateID = null;
will not work without the line "IsModified = true", because the property UpdateID, is already null when you created the empty TestProcess object, you needs to say to EF that this column must be updated, and this is the purpose of this line.