I would go with your current approach, except that I would exclude the while loop. If you want only one entry to be returned, do an additional Read to make sure it returns false. This is similar to the semantics of the LINQ Single statement.
if (!reader.Read()) throw new InvalidOperationException("No records were returned."); image.Id = reader.GetInt32(ordId); image.Name = reader.GetString(ordName); image.Path = reader.GetString(ordPath); if (reader.Read()) throw new InvalidOperationException("Multiple records were returned.");
Assuming that the id column in your database is the primary key (unique), there is no need to specify the TOP clause in the SQL query; SQL Server Query Optimizer reports that only one record is returned due to a WHERE . However, if you do not have a primary key or a unique index / constraint in the id column, you should issue a TOP (2) clause to limit the number of rows returned. You should avoid using TOP (1) because you will not be able to detect (and raise the error) additional matches.
string sql = @"SELECT TOP (2) * FROM Images WHERE id = @id"
source share