I keep getting this error: “Invalid attempt to call Read when reader is closed”

我只是一个虾纸丫 提交于 2019-12-02 11:35:47

Let's try to improve this code a little:

private IEnumerable<BursaUser> GetUsers()
{
    using (var conn = new SqlConnection(SomeConnectionString))
    using (var cmd = conn.CreateCommand())
    {
        conn.Open();
        cmd.CommandText = "SELECT WorkerNum, CompanyName, ... FROM Users";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                var user = new User
                {
                    UserId = reader.GetInt32(reader.GetOrdinal("WorkerNum")),
                    CompanyName = reader.GetString(reader.GetOrdinal("CompanyName")),
                    // TODO: complete other fields
                };
                // TODO: do the tests and complete the complex properties
                yield return user;
            }
        }
    }
}

Now this code is perfectly reentrant and thread safe. You don't need any locking.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!