根据我遵循的课程连接到数据库

Connecting to a database based on a course I follow

我正在学习在线课程,他们在课程中解释了如何从数据库中检索数据。创建连接和命令由 DbProviderFactories class 完成。我理解课程中的代码,但是使用 using 进行连接、命令和 reader 是必要的吗?另外,是否需要空检查?代码看起来很杂乱,如果你的数据库中有很多模型(大陆、国家、货币等),它会需要很多 copy/paste,这是不好的吗?

所以真正的问题是,下面的代码是好是坏,还有哪些地方可以改进?目标是使用 SQLite 作为数据库提供程序。这适用于以下方法吗?

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 用于连接、命令和 reader 必要吗?

是的。 这里我注释了代码

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()));
            }

此外,空值检查是否必要?

It could return null data so yes absolutely

代码看起来很乱

Such is the coder life brotha. Using loops for objects will save on space.