在动态场景中使用带有GridView的ObjectDataSource

时间:2010-09-29 16:41:57

标签: c# asp.net gridview objectdatasource

我有一个搜索页面,其任务是根据个人姓名,客户ID,地址等搜索350万条记录。查询范围从复杂到简单。

目前,此代码依赖于SqlDataSource和GridView。当用户键入serach term并按Enter键时,TextBoxChanged甚至会运行一个Search(term,type)函数,该函数更改SqlDataSource使用的查询,添加参数并重新绑定GridView。

效果很好,但我已经痴迷于更有效地重写代码。我希望分页由SQL Server完成,而不是在DataSet模式下SqlDataSource的低效率。

输入ObjectDataSource。警告:我从未在今天之前使用过。

我花了很多时间把这个课程组合在一起:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MultiSearchData
/// </summary>
public class MultiSearchData
{
    private string _connectionString = string.Empty;
    private string _sortColumns = string.Empty;
    private string _selectQuery = string.Empty;
    private int _lastUpdate;
    private int _lastRowCountUpdate;
    private int _lastRowCount;
    private SqlParameterCollection _sqlParams;

    public MultiSearchData()
    {

    }

    private void UpdateDate()
    {
        _lastUpdate = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
    }

    private string ReplaceFirst(string text, string search, string replace)
    {
        int pos = text.IndexOf(search);
        if (pos < 0)
        {
            return text;
        }
        return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
    }

    public string SortColumns
    {
        get { return _sortColumns; }
        set { _sortColumns = value; }
    }

    public SqlParameterCollection SqlParams
    {
        get { return _sqlParams; }
        set { _sqlParams = value; }
    }

    public string ConnectionString
    {
        get { return _connectionString; }
        set { _connectionString = value; }
    }

    public string SelectQuery
    {
        get { return _selectQuery; }
        set
        {
            if (value != _selectQuery)
            {
                _selectQuery = value;
                UpdateDate();
            }
        }
    }

    public DataTable GetFullDataTable()
    {
        return GetDataTable(AssembleSelectSql());
    }

    public DataTable GetPagedDataTable(int startRow, int pageSize, string sortColumns)
    {
        if (sortColumns.Length > 0)
            _sortColumns = sortColumns;

        return GetDataTable(AssemblePagedSelectSql(startRow, pageSize));
    }

    public int GetRowCount()
    {

        if (_lastRowCountUpdate == _lastUpdate)
        {
            return _lastRowCount;
        }
        else
        {
            string strCountQuery = _selectQuery.Remove(7, _selectQuery.IndexOf("FROM") - 7);
            strCountQuery = strCountQuery.Replace("SELECT FROM", "SELECT COUNT(*) FROM");

            using (SqlConnection conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(strCountQuery, conn))
                {
                    if (_sqlParams.Count > 0)
                    {
                        foreach (SqlParameter param in _sqlParams)
                        {
                            cmd.Parameters.Add(param);
                        }
                    }
                    _lastRowCountUpdate = _lastUpdate;
                    _lastRowCount = (int)cmd.ExecuteScalar();
                    return _lastRowCount;
                }
            }
        }
    }

    public DataTable GetDataTable(string sql)
    {
        DataTable dt = new DataTable();

        using (SqlConnection conn = new SqlConnection(_connectionString))
        {
            using (SqlCommand GetCommand = new SqlCommand(sql, conn))
            {
                conn.Open();

                if (_sqlParams.Count > 0)
                {
                    foreach (SqlParameter param in _sqlParams)
                    {
                        GetCommand.Parameters.Add(param);
                    }
                }
                using (SqlDataReader dr = GetCommand.ExecuteReader())
                {
                    dt.Load(dr);
                    conn.Close();
                    return dt;
                }
            }
        }


    }

    private string AssembleSelectSql()
    {
        StringBuilder sql = new StringBuilder();

        sql.Append(_selectQuery);

        return sql.ToString();
    }

    private string AssemblePagedSelectSql(int startRow, int pageSize)
    {
        StringBuilder sql = new StringBuilder();
        string originalQuery = ReplaceFirst(_selectQuery, "FROM", ", ROW_NUMBER() OVER (ORDER BY " + _sortColumns + ") AS ResultSetRowNumber FROM");
        sql.Append("SELECT * FROM (");
        sql.Append(originalQuery);
        sql.Append(") AS PagedResults");
        sql.AppendFormat(" WHERE ResultSetRowNumber > {0} AND ResultSetRowNumber <= {1}", startRow.ToString(), (startRow + pageSize).ToString());

        return sql.ToString();
    }
}

我不知道它是否漂亮。有用。我在ObjectCreating方法中给它一个查询:

protected void dataMultiSearchData_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
    MultiSearchData info;
    info = Cache["MultiSearchDataObject"] as MultiSearchData;

    if (null == info)
    {
        info = new MultiSearchData();
    }


    info.SortColumns = "filteredcontact.fullname";
    info.ConnectionString = "Data Source=SERVER;Initial Catalog=TheDatabase;Integrated Security=sspi;Connection Timeout=60";
    info.SelectQuery = @"SELECT filteredcontact.contactid,
                              filteredcontact.new_libertyid,
                              filteredcontact.fullname,
                              '' AS line1,
                              filteredcontact.emailaddress1,
                              filteredcontact.telephone1,
                              filteredcontact.birthdateutc AS birthdate,
                              filteredcontact.gendercodename
                        FROM  filteredcontact 
                        WHERE fullname LIKE 'Griffin%' AND filteredcontact.statecode = 0";

    e.ObjectInstance = info;
}
protected void dataMultiSearchData_ObjectDisposing(object sender, ObjectDataSourceDisposingEventArgs e)
{
    MultiSearchData info = e.ObjectInstance as MultiSearchData;

    MultiSearchData temp = Cache["MultiSearchDataObject"] as MultiSearchData;

    if (null == temp)
    {
        Cache.Insert("MultiSearchDataObject", info);
    }

    e.Cancel = true;
}

一旦该类具有查询,它就会将其包装在分页友好的SQL中,我们将参加比赛。我已经实现了缓存,因此它可以跳过一些昂贵的查询。等等。

我的问题是,这完全破坏了我很小的搜索(术语,类型)世界。在ObjectCreating方法中设置查询完全破坏了我的氛围。

我一直在努力想出一个更好的方法来整天做这件事,但我总是把它弄得一团糟......在ObjectCreating模型中做到这一切只会让我感到厌烦。

你会怎么做?如何保持这种新方法的效率,同时具有我以前模型的组织简单性?

我是否过于强迫症?

1 个答案:

答案 0 :(得分:0)

我确定无法完成。此外,在对这个类进行基准测试后,我发现它的表现并不比SqlDataSource好,但维护起来要困难得多。

因此我放弃了这个项目。我希望有人在某些时候发现这段代码很有用。