I’m doing some work with EF 4.1 and I’d like to perform a batch update on 3 tables (for the purpose of implementing a soft delete). From doing some quick research it looks like direct SQL queries are best. My implementation is below and I was hoping for some feedback on whether this is best practice. Thanks for the help …
using (var scope = new TransactionScope())
{
using (var db = new TimeCatchDb())
{
db.Database.ExecuteSqlCommand("UPDATE EmployeeRecords SET Deleted = 1 WHERE NoteTypeId = @p0", new SqlParameter { ParameterName = "p0", Value = id});
db.Database.ExecuteSqlCommand("UPDATE Notes SET Deleted = 1 WHERE NoteTypeId = @p0", new SqlParameter { ParameterName = "p0", Value = id });
db.Database.ExecuteSqlCommand("UPDATE NoteTypes SET Deleted = 1 WHERE Id = @p0", new SqlParameter { ParameterName = "p0", Value = id });
}
scope.Complete();
}
If you want batch why don’t you place all updates into single
ExecuteSqlCommand? Each call toExecuteSqlCommandmakes its own round trip to the database = it is not a batch. Also be aware that if any of modified records is currently loaded in the context changes will not be reflected = loaded entities will still haveDeleted = 1. Direct SQL commands affect only database.This is best achieved in normal EFv4 + EDMX by mapping custom stored procedure to
Deleteoperation (but it also doesn’t support batches) but once you don’t have EDMX you cannot do that.