I have read this thread: Is it bad coding practice to create something in a get if it does not exist?
But, my question involve a method which gets a record from a database or creates it if it doesn't exist. I have two separate methods for checking if a record exists and the second to insert if it doesn't exists. But consequently, it sometimes creates many the same records if I call my api very fast. So, I created one method GetOrCreate and used the transaction. Do you think in that case the GetOrCreate method is a good approach?
public async Task<int> GetOrCreateRegionIdAsync(int companyId)
{
using (SqlConnection connection = new SqlConnection("....."))
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction())
{
var regionId = await GetRegionIdAsync(connection, transaction, companyId); // GET
if (regionId.HasValue)
{
return regionId.Value;
}
var region = new Region()
{
CompanyID = companyId
};
var newRegionid = await connection.InsertAsync<int>(region, transaction); // CREATE
return newRegionid;
}
}
}
I need to get the region id (or create it if it doesn't exist) because then I need to save a record in a table called FormLinks which has a column 'regionId'.
-- the Regions table
SELECT [id]
,[name]
,[companyId]
,[available]
,[displayOrder]
,[createDate]
FROM [Regions]
-- the FormLinks table:
SELECT [id]
[regionId]
,[available]
,[createDate]
,[url]
FROM [FormLinks]