Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return an IEnumerable<> using ADO.NET?

Tags:

c#

ado.net

dapper

I've been using Dapper and with my current project I'm going to have to use ADO.NET. My question is how do I return an IEnumerable using ADO.NET? Here is what I have using Dapper. Can someone help me with converting this to do the same but with ADO?

public IEnumerable<Favorites> GetFavorites()
{
    using (SqlConnection sqlConnection = new SqlConnection(connString))
    {
        sqlConnection.Open();
        var work = sqlConnection.Query<Favorites>("Select * from favorites");
        return work;
    }
}
like image 740
haydnD Avatar asked Jul 24 '12 15:07

haydnD


People also ask

How do I return an IEnumerable class in C#?

The first method in the class that will be called is IEnumerable<int>. GetEnumerator() . If the call is coming from the same thread that instantiated the class, it will reset the state to 0 and return this . The next thing the calling code would do is to step the enumerator forward through IEnumerator<int>.

How do I return empty IEnumerable?

Using List for returning an empty Enumerable is wasting. Array. Empty<T>() or Enumerable. Empty<T>() are the most resource sparing solutions.

What does IEnumerable return?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.


1 Answers

You can use yield return like so:

public IEnumerable<Favorites> GetFavorites()
{
    using (SqlConnection sqlConnection = new SqlConnection(connString))
    {
        sqlConnection.Open();
        using (SqlCommand cmd = sqlConnection.CreateCommand())
        {
            cmd.CommandText = "Select * from favorites";
            cmd.CommandType = CommandType.Text;
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Create a Favorites instance
                    var favorites = new Favorites();
                    favorites.Foo = reader["foo"];
                    // ... etc ...
                    yield return favorites;
                }
            }
        }
    }
}

Obviously, you can refactor this by creating a Favorites constructor that accepts an IDataReader or SqlDataReader, or creating a utility method to populate the values, or whatever, but this is the basic structure.

like image 161
Steve Czetty Avatar answered Oct 02 '22 17:10

Steve Czetty