Reputation: 1
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:
Phone
entity, but also searching for the Id
after.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