Dake
Dake

Reputation: 1

Could my C# method that saves an entity into SQL database return Id of the inserted row?

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)?

Upvotes: 0

Views: 34

Answers (0)

Related Questions