Return income from try / catch block

Like Eric Lippert described in this article , yield return not allowed in try/catch .

Is there a good way to get something like this without having to manually write IEnumerator :

 public IEnumerable<Data> GetData() { var transaction = Session.BeginTransaction()); try { IQuery q = CreateQuery(session); foreach (var result in q.Enumerable()) yield return ProjectResult(result); // <-- doesn't work session.Commit(); } catch (Exception ex) { transaction.Rollback(); throw; } finally { transaction.Dispose(); } } 
+7
source share
2 answers

I would just change the transaction processing logic as follows:

 public IEnumerable<Data> GetData() { var transaction = Session.BeginTransaction(); bool rollback = true; try { IQuery q = CreateQuery(session); foreach (var result in q.Enumerable()) { yield return ProjectResult(result); } rollback = false; session.Commit(); } finally { if (rollback) { transaction.Rollback(); } transaction.Dispose(); } } 

Or, if your transaction supports the idea of ​​"cancel the rollback method if it did not complete":

 public IEnumerable<Data> GetData() { using (var transaction = Session.BeginTransaction(); { IQuery q = CreateQuery(session); foreach (var result in q.Enumerable()) { yield return ProjectResult(result); } // Commits the tnrasaction, so disposing it won't roll it back. session.Commit(); } } 
+11
source

Re factor

 foreach (var result in q.Enumerable()) yield return ProjectResult(result); 

into a separate method and just return the result.

-one
source

All Articles