Issue: (With Sql 2005)
In my case I delete all records from a Table through plain SQL since EF doesn't provide a functionality for this. After that I add some new entities - but when it fails, the table shouldn't be empty. The use of MSDTC (TransactionScope) seems not possible for me. I reduced the transaction to the DB:
My code:
using (var transaction = context.Connection.BeginTransaction())
{
// delete all
base.DeleteAll(context);
// add all
foreach (var item in items)
{
context.TESTEntity.AddObject(item);
}
try
{
context.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
Logger.Write("Error in Save: " + ex, "Error");
transaction.Rollback();
return false;
}
}
And here the helper functions
protected void DeleteAll(ObjectContext context) where TEntity : class
{
string tableName = GetTableName(context);
int rc = context.ExecuteStoreCommand(string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0}", tableName));
}
protected string GetTableName(ObjectContext context) where TEntity : class
{
string snippet = "FROM [dbo].[";
string sql = context.CreateObjectSet().ToTraceString();
string sqlFirstPart = sql.Substring(sql.IndexOf(snippet) + snippet.Length);
string tableName = sqlFirstPart.Substring(0, sqlFirstPart.IndexOf("]"));
return tableName;
}