I had previously asked about
Converting using SqlConnection to Func delegate
How can I use the following delegate to make multiple calls using the same transaction?
To complicate matters, one of the calls I wish to return a value.
I have the following Delegate function definition
protected TResult UsingSqlTransaction<TResult>(Func<SqlTransaction, TResult> myFunction)
{
using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
{
sqlConn.Open();
using (SqlTransaction sqlTrans = sqlConn.BeginTransaction())
{
var result = myFunction(sqlTrans);
sqlTrans.Commit();
return result;
}
}
}
Current usage
public Guid? InsertUpdate(News entity)
{
return UsingSqlTransaction(sqlTrans => data.InsertUpdate(sqlTrans, entity));
}
Solution – See the accepted answer
public Guid? InsertUpdate(News entity)
{
return UsingSqlTransaction(sqlTrans =>
{
var token = data.InsertUpdate(sqlTrans, entity);
data.DoSomethingElse(sqlTrans, entity);
return token;
});
}
//-- The above UsingSqlTransaction remains unchanged
You can use a ‘block’ lambda. Instead of:
You can use (note curly braces and semicolons):
Re: your update. I’d write that like this (note that you can store
tokenand return it at the end of your lambda, just like a normal method):