TransactionScope

Posts   
 
    
he00273
User
Posts: 133
Joined: 02-Oct-2008
# Posted on: 06-Jul-2009 10:37:38   

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;
    }
Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 06-Jul-2009 10:48:23   

using (TransactionScope transScope = new TransactionScope()) { newCaseIdentity.CaseSequence += 1; adaptor.SaveEntity(newCaseIdentity); transScope.Complete(); }

I don't see a need to use a Transaction for one Update statement.

he00273
User
Posts: 133
Joined: 02-Oct-2008
# Posted on: 07-Jul-2009 02:30:04   

You are correct. It would be a singleton transaction in anycase. I guess I carried away. Thanks for the sanity check. simple_smile