I want to fetch an entity from the database using a unique constraint.
I then want to update the entity fetched or a new one instantiated back to the database.
I need to do this inside a transaction. I am not sure where to place the TransactionScope. Should I place it at before I get the DataAccessAdaptor or wait until I am doing the update.
I want to make sure that any connection is closed.
Could you please review the following and tell me if it needs to be changed or not.
public string GetYearCaseIdentifier(string CaseType, int year)
{
if (!databaseOnline)
throw new FaultException("Database is offline");
string caseIdentifier = String.Empty;
CaseIdentifierEntity newCaseIdentity = new CaseIdentifierEntity();
newCaseIdentity.CaseType = CaseType;
newCaseIdentity.CaseYear = year;
DataAccessAdapter adaptor = new DataAccessAdapter(databaseConnectionString, true);
try
{
adaptor.FetchEntityUsingUniqueConstraint(newCaseIdentity,
newCaseIdentity.ConstructFilterForUCCaseTypeCaseYear());
if (newCaseIdentity.Fields.State != EntityState.Fetched)
{
newCaseIdentity = new CaseIdentifierEntity();
newCaseIdentity.CaseYear = year;
newCaseIdentity.CaseType = CaseType;
newCaseIdentity.CaseSequence = 1;
}
caseIdentifier = String.Format("{0}{1}{2}", (year % 100).ToString("00"), CaseType, newCaseIdentity.CaseSequence.ToString("00000"));
}
catch (ORMEntityOutOfSyncException ex)
{
throw new FaultException(ex.Message);
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
try
{
using (TransactionScope transScope = new TransactionScope())
{
newCaseIdentity.CaseSequence += 1;
adaptor.SaveEntity(newCaseIdentity);
transScope.Complete();
}
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
finally
{
adaptor.CloseConnection();
}
return caseIdentifier;
}