带有ODS,BusinessLayer和Dynamic Linq的ListView不排序

时间:2011-05-04 16:50:08

标签: c# asp.net linq listview objectdatasource

症状:ListView未排序

数据层: Linq生成的类,包括Northwind Employee表和System.Linq.Dynamic类

业务层:

namespace BusinessLayer
{
    [Serializable]
    public class EmployeeData
    {
        public int EmployeeId { get; set; }
        public int? ReportsToId { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Title { get; set; }
        public DateTime? BirthDate { get; set; }
        public DateTime? HireDate { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
    }

    [Serializable]
    public class EmployeeFilter 
    {
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string City { get; set; }
    }

    [Serializable]
    public class EmployeeList
    {
        public int ListCount(EmployeeFilter filter, string sortType, int startRowIndex, int maximumRows)
        {
            var rows = listQuery();
            return rows.Count();
        }

        public IEnumerable<EmployeeData> List(EmployeeFilter filter, string sortType, int startRowIndex, int maximumRows)
        {
            var rows = listQuery();
            if (!string.IsNullOrEmpty(sortType)) rows = listSort(rows, sortType);
            return (maximumRows > 0)
                ? rows.Distinct().Skip(startRowIndex).Take(maximumRows).ToList()
                : rows.Distinct().Skip(startRowIndex).ToList();
        }

        public IQueryable<EmployeeData> listQuery()
        {
            var dc = new NorthwindDataContext();
            var allrows = from emp in dc.Employees
                          select new EmployeeData()
                          {
                              EmployeeId = emp.EmployeeID,
                              ReportsToId = emp.ReportsTo,
                              FirstName = emp.FirstName,
                              LastName = emp.LastName,
                              Address = emp.Address,
                              City = emp.City,
                              PostalCode = emp.PostalCode,
                              BirthDate = emp.BirthDate,
                              HireDate = emp.HireDate,
                              Title = emp.Title,
                          };
            return allrows;
        }

        public IQueryable<EmployeeData> listSort(IQueryable<EmployeeData> rows, string sortType)
        {
            bool sortDescending = false;
            if (!string.IsNullOrEmpty(sortType))
            {
                string[] values = sortType.Split(' ');
                sortType = values[0];
                if (values.Length > 1)
                {
                    sortDescending = (values[1] == "DESC");
                }
            }


            if (!string.IsNullOrEmpty(sortType))
            {
                rows = rows.OrderBy(string.Format("{0}{1}",sortType,(sortDescending) ? " DESC" : ""));
            }

            return rows;
        }
    }
}

用户层:

<asp:ListView ID="lstEmployees" runat="server" DataSourceID="odsEmployees" >
    <LayoutTemplate>
        <table>
            <tr>
                <th align="left">
                    <asp:LinkButton runat="server" ID="LinkButton1" CommandName="Sort" CommandArgument="FirstName">First Name</asp:LinkButton>
                </th>
                <th align="left">
                    <asp:LinkButton runat="server" ID="LinkButton5" CommandName="Sort" CommandArgument="LastName">Last Name</asp:LinkButton>
                </th>
                <th align="left">
                    <asp:LinkButton runat="server" ID="LinkButton6" CommandName="Sort" CommandArgument="BirthDate">Birth Date</asp:LinkButton>
                </th>
            </tr>
            <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
        </table>
    </LayoutTemplate>
    <ItemTemplate>
        <tr>
            <td><%#Eval("FirstName") %></td>
            <td><%#Eval("LastName") %></td>
            <td><%#string.Format("{0:d}", Eval("BirthDate"))%></td>
        </tr>
    </ItemTemplate>
    <EmptyDataTemplate>
        Sorry - no employees found
    </EmptyDataTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="odsEmployees" runat="server" EnablePaging="True" OldValuesParameterFormatString="original_{0}"
    SelectCountMethod="ListCount" SelectMethod="List" SortParameterName="sortType"
    TypeName="BusinessLayer.EmployeeList">
    <SelectParameters>
        <asp:SessionParameter Name="filter" SessionField="employeeFilter" Type="Object" />
        <asp:Parameter Name="sortType" Type="String" />
        <asp:Parameter Name="startRowIndex" Type="Int32" />
        <asp:Parameter Name="maximumRows" Type="Int32" />
    </SelectParameters>
</asp:ObjectDataSource>

分析: 我对此进行了详尽的测试。调用排序代码并正确排序从List方法返回的查询;但是,表单上显示的数据未排序。

listSort返回此SQL查询:

SELECT [t0].[EmployeeID] AS [EmployeeId], [t0].[ReportsTo] AS [ReportsToId], [t0].[LastName], [t0].[FirstName], [t0].[Title], [t0].[BirthDate], [t0].[HireDate], [t0].[Address], [t0].[City], [t0].[PostalCode]
FROM [dbo].[Employees] AS [t0]
ORDER BY [t0].[BirthDate] DESC 

进一步测试显示我使用GridView

得到了相同的结果

2 个答案:

答案 0 :(得分:1)

原来,对象数据源(ODS)不对IEnumerable进行排序。 Linq代码必须返回DataTable或DataSet。我找到了两篇文章,展示了如何做到这一点。一个接近但不完整。另一个像魔术一样工作: Linq To DataTable

以下是我发现并设法在几分钟内完成工作的代码:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace BusinessLayer
{
    public static class ConvertDataTable
    {
        public static DataTable ToTable<T>(this IEnumerable<T> varlist, CreateRowDelegate<T> fn)
        {

            DataTable dtReturn = new DataTable();
            // Could add a check to verify that there is an element 0

            T TopRec = varlist.ElementAt(0);

            // Use reflection to get property names, to create table

            // column names

            PropertyInfo[] oProps =
            ((Type)TopRec.GetType()).GetProperties();

            foreach (PropertyInfo pi in oProps)
            {

                Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {

                    colType = colType.GetGenericArguments()[0];

                }

                dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
            }

            foreach (T rec in varlist)
            {

                DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps)
                {
                    dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
                }
                dtReturn.Rows.Add(dr);

            }

            return (dtReturn);
        }

        public delegate object[] CreateRowDelegate<T>(T t);
    }
}

这是新的List方法:

public DataTable List(EmployeeFilter filter, string sortType, int startRowIndex, int maximumRows)
{
    var rows = listQuery();
    if (!string.IsNullOrEmpty(sortType)) rows = listSort(rows, sortType).Skip(startRowIndex);
    if (maximumRows > 0) rows = rows.Take(maximumRows);
    DataTable dt = rows.ToTable(r => new object[] { rows });
    return dt;
}

答案 1 :(得分:0)

老实说,我不知道ListView如何与ODS一起使用。我只使用了带有LDS的ListView,但我确实看到了一个可能的代码问题。如果你期望在这里发射一个或另一个,你将无法得到它。

if (!string.IsNullOrEmpty(sortType)) // why repeat the same 'if' statement logic?
{
     string[] values = sortType.Split(' ');
     sortType = values[0];
     if (values.Length > 1)
     {
         sortDescending = (values[1] == "DESC");
     }
}


if (!string.IsNullOrEmpty(sortType)) // why repeat the same 'if' statement logic?
{
    rows = rows.OrderBy(string.Format("{0}{1}",sortType,(sortDescending) ? " DESC" : ""));
}