Can I combine these three similar functions into a single function?

155 views Asked by At

Can I combine the three very similar functions below into a single function?

All three functions update a particular column in the database. The anonymous object in the update statement is used to update the corresponding column. The member name in the anonymous object should not be changed as it is the name of the column in the database.

I am using ormlite-servicestack for database connection. The DB I use Microsoft SQLServer 2012.

Function 1:

//Updating the call status.
private void UpdateCallStatus(string claimId, bool isDisconnected)
{
    _LogFactory.LogInfo(this.GetType(), "Updating call status....\n");

    IDbConnectionFactory maConnectionFactory = new DatabaseConnection().getConnection();
    using (var db = maConnectionFactory.Open())
    {
        db.Update<IVRSCallDetails>(new { IsDisconnected = isDisconnected }, where: callDetail => callDetail.ClaimId == claimId);
    }
}

Function 2:

//Updating the selected dtmf by the client using the claimid.
private void UpdateDtmf(string claimId, string selectedDtmf)
{
    _LogFactory.LogInfo(this.GetType(), "Updating Selected DTMF:" + selectedDtmf + "\n");

    IDbConnectionFactory maConnectionFactory = new DatabaseConnection().getConnection();
    using (var db = maConnectionFactory.Open())
    {
        db.Update<IVRSCallDetails>(new { SelectedDTMF = selectedDtmf }, where: callDetail => callDetail.ClaimId == claimId);
    }
}

Function 3:

//Updating the isCallMade value..
private void updateIsCallMade(string claimId, bool isCallMade)
{
    _LogFactory.LogInfo(this.GetType(), "Call has been made to the client with claim id: " + claimId + "\n");

    IDbConnectionFactory maConnectionFactoruy = new DatabaseConnection().getConnection();
    using (var db = maConnectionFactoruy.Open())
    {
        db.Update<IVRSCallDetails>(new { IsCallMade = isCallMade }, where: callDetail => callDetail.ClaimId == claimId);
    }
}
1

There are 1 answers

3
Jamiec On BEST ANSWER

You could change it to a generic method (to be able to pass the type) and also a Func<object> in place of the second parameter to generate the anonymous object.

private void updateData<T>(string claimId, Func<object> data)
{
    _LogFactory.LogInfo(this.GetType(), "Call has been made to the client with claim id: " + claimId + "\n");

    IDbConnectionFactory maConnectionFactoruy = new DatabaseConnection().getConnection();
    using (var db = maConnectionFactoruy.Open())
    {
        db.Update<T>(data(), where: callDetail => callDetail.ClaimId == claimId);
    }
}

usage

updateData<IVRSCallDetails>("123", () => new { IsCallMade = true});
updateData<IVRSCallDetails>("123", () => new { SelectedDTMF = selectedDtmf});