Improve data access layer select method Pattern

后端 未结 7 920
眼角桃花
眼角桃花 2020-12-05 05:46

Lately I find myself writing data access layer select methods where the code all takes this general form:

public static DataTable GetSomeData( ... arguments)         


        
7条回答
  •  悲&欢浪女
    2020-12-05 06:40

    Had to add my own:
    Return DataReader from DataLayer in Using statement

    The new pattern enables me to only have one record in memory at a time, but still encases the connection in a nice 'using' statement:

    public IEnumerable GetSomeData(string filter, Func factory)
    {
        string sql = "SELECT * FROM [SomeTable] WHERE SomeColumn= @Filter";
    
        using (SqlConnection cn = new SqlConnection(GetConnectionString()))
        using (SqlCommand cmd = new SqlCommand(sql, cn))
        {
            cmd.Parameters.Add("@Filter", SqlDbType.NVarChar, 255).Value = filter;
            cn.Open();
    
            using (IDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    yield return factory(rdr);
                }
                rdr.Close();
            }
        }
    }
    

提交回复
热议问题