0

I'm using IDbConnection interface for saving data into my SQL tables, that has a method called Execute, which executes the query and returns the number of rows affected

I have the following code:

public class Phone
{
    public required int Id { get; set; }
    public required string Number { get; set; }
}

public class SqlServerDataAccess : ISqlDataAccess
{
    public async Task<int> SaveDataAsync<T>(string sqlStatement, T parameters, string connectionString)
    {
        using IDbConnection connection = new SqlConnection(connectionString);
        return await connection.ExecuteAsync(sqlStatement, parameters);
    }
}

public class SqlPhoneData : IPhoneData
{
    private readonly string _connectionString;
    private readonly ISqlDataAccess _dataAccess;

    public SqlPhoneData(ISqlDataAccess dataAccess, string connectionString)
    {
        _connectionString = connectionString;
        _dataAccess = dataAccess;
    }

    public async Task<int> SavePhoneAsync(Phone phone)
    {
        string sqlStatement =
            "INSERT INTO dbo.Phone " +
            "(Number) " +
            "VALUES (@Number);";

        DynamicParameters parameters = new(phone);

        return await _dataAccess.SaveDataAsync(sqlStatement, parameters, _connectionString);
    }
}

Speaking of SavePhoneAsync method, I don't really need the number of rows affected. Instead, I'd like to return the Id of the inserted entity. Although I have the following concerns about doing this:

  1. It may violate SRP as the method now not only saving the Phone entity, but also searching for the Id after.
  2. It might be not obvious for other developers that the method returns the Id, while they expect to get the number of rows affected.

So, how should I proceed? Do I need to return the number of rows affected even if I don't use it now? Can I replace it with the Id of the inserted value? Or should I return both like that: public async Task<(int rowsAffected, int Id)> SavePhoneAsync(Phone phone)?

Dake
  • 1
  • 1
  • Well, SRP is to be considered, but not at the expense of a clear performance loss. Having two separate methods, one to insert and one to read the id, means that you hit the database two times when the operation could easily performed in one single step. – Steve Feb 12 '23 at 16:28
  • For SQL Server you can just do `@"INSERT INTO dbo.Phone (Number) OUTPUT inserted.Id VALUES (@Number);"` Note by the way that you can use a verbatim string with `@` to avoid lots of concatenation of newlines. – Charlieface Feb 12 '23 at 17:48

0 Answers0