I’m following an online course and in the course they explain how you can retrieve data from a database. Creating the connection and commands are done by a DbProviderFactories
class. I understand the code in the course but is using using
for the connection, command and reader necessary? Also, are the null checks necessary? The code looks cluttered and if you have a lot of models in your database (Continent, Country, Currency, …) it would require a lot of copy/paste which is bad?
So the question really is, is the code below rather good or bad and what could be improved upon? The goal is to use SQLite as database provider. Does this work with the approach below?
public static ObservableCollection<Continent> GetContinents()
{
var continents = new ObservableCollection<Continent>();
var provider = ConfigurationManager.ConnectionStrings["DbConnection"].ProviderName;
var connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
using (var connection = DbProviderFactories.GetFactory(provider).CreateConnection())
{
if (connection == null) return null;
connection.ConnectionString = connectionString;
connection.Open();
using (var command = DbProviderFactories.GetFactory(provider).CreateCommand())
{
if (command == null) return null;
command.CommandType = CommandType.Text;
command.Connection = connection;
command.CommandText = "SELECT * FROM Continent";
using (var reader = command.ExecuteReader())
while (reader.Read())
continents.Add(new Continent(reader["Code"].ToString(), reader["EnglishName"].ToString()));
}
}
return continents;
}
using using for the connection, command and reader necessary?
Yes. Here I commented the code
using (var command = DbProviderFactories.GetFactory(provider).CreateCommand()) // here you've created the command
{
if (command == null) return null;
command.CommandType = CommandType.Text;
command.Connection = connection;
command.CommandText = "SELECT * FROM Continent";
using (var reader = command.ExecuteReader()) //Here you're reading what the command returned.
while (reader.Read())
continents.Add(new Continent(reader["Code"].ToString(), reader["EnglishName"].ToString()));
}
Also, are the null checks necessary?
It could return null data so yes absolutely
The code looks cluttered
Such is the coder life brotha. Using loops for objects will save on space.