On data binding: LINQ to Entities does not recognize the method 'System.String ToString()' method

有些话、适合烂在心里 提交于 2020-01-16 04:02:24

问题


I'm using LINQ to Entities

My GridView is the following :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
    EmptyDataText="No Data" CellPadding="3" CellSpacing="1"
    AllowSorting="True" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
    OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" CssClass="gridview"
    OnSorting="GridView1_Sorting" HorizontalAlign="Center">
    <AlternatingRowStyle BackColor="#F0F0F0" />
    <Columns>
        <asp:BoundField HeaderText="ID" DataField="ID" ReadOnly="True" SortExpression="ID" />
        <asp:BoundField HeaderText="Name" DataField="SoftwareName" SortExpression="Name" />
        <asp:BoundField HeaderText="Key" DataField="Key" SortExpression="Key" />
        <asp:BoundField HeaderText="Date" DataField="Date" ItemStyle-CssClass="date_td" SortExpression="Date"
            ReadOnly="True">
            <ItemStyle CssClass="date_td"></ItemStyle>
        </asp:BoundField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton runat="server" ToolTip="edit" ID="EditButton" CommandName="Edit"
                    ImageUrl="~/images/edit.png" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:ImageButton runat="server" ID="UpdateButton" ToolTip="Submit" CommandName="Update"
                    ImageUrl="~/images/ok.gif" />
                <asp:ImageButton runat="server" ID="Cancel" ToolTip="Submit" CommandName="Cancel"
                    ImageUrl="~/images/cancel.gif" />
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton runat="server" ToolTip="Delete" ID="btnDelete" CommandName="cDelete"
                    ImageUrl="~/images/delete.png" OnCommand="OnDelete" CommandArgument='<%# Bind("id") %>'
                    OnClientClick="return confirm('Are you sure ?')" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <PagerSettings Mode="NumericFirstLast" />
</asp:GridView>

I fill the GridView with the following c# code :

private IQueryable SortGridView()
{
    IQueryable<Softwares> softwares = Search();

    if (softwares == null) return null;

    string sortExpression = (ViewState["SortExpression"] as string) == null
                                ? "ID"
                                : ViewState["SortExpression"] as string;
    string lastDirection = (ViewState["SortDirection"] as string) == null
                                ? "ASC"
                                : ViewState["SortDirection"] as string;

    switch (sortExpression)
    {
        case "ID":
            softwares = (lastDirection == "ASC")
                                ? softwares.OrderBy(q => q.id)
                                : softwares.OrderByDescending(q => q.id);
            break;

        case "Name":
            softwares = lastDirection == "ASC"
                            ? softwares.OrderBy(q => q.softwareName)
                            : softwares.OrderByDescending(q => q.softwareName);
            break;

        case "Key":
            softwares = (lastDirection == "ASC")
                            ? softwares.OrderBy(q => q.Keys.Key)
                            : softwares.OrderByDescending(q => q.Keys.Key);
            break;

        case "Date":
            softwares = lastDirection == "ASC"
                            ? softwares.OrderBy(q => q.Date)
                            : softwares.OrderByDescending(q => q.Date);
            break;
    }

    return from q in softwares
            select new
                        {
                            ID = q.id,
                            SoftwareName = q.softwareName,
                            Key = q.Keys.Key
                            Date = q.Date.ToString()
                        };
}

protected void ButtonSearch_Click(object sender, EventArgs e)
{
    GridView1.DataSource = SortGridView();
    GridView1.DataBind();// <<--- Exception
}

But in ButtonSearch_Click I get the following exception :

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

I've done it before with the LINQ to SQL without any problems, what is wrong with it here?


回答1:


LINQ to Entities queries are internally converted into sql statements. In your case its just that, LINQ to Entity provider is not able to map the "toString" call into a suitable SQL statement. You can retrieve the data from LINQ to entity and then enumerate offline and make the necessary changes i.e. :

var data = (from q in softwares
            select new
                        {
                            ID = q.id,
                            SoftwareName = q.softwareName,
                            Key = q.Keys.Key
                            Date = q.Date
                        }).ToList();

and then convert the Date part by calling ToString() method offline.

data.ForEach(item => item.Date = item.Date.ToString());

You are returning anonymous type from your method. Anonymous types are accessible only within the class where they are defined. You can try something like the code I have given below :

private IList<SoftwareInfo> SortGridView()
{
    // regular code

    return (from q in softwares
            select new SoftwareInfo
                        {
                            ID = q.id,
                            SoftwareName = q.softwareName,
                            Key = q.Keys.Key,
                            Date = q.Date
                        }).ToList();
}


public class SoftwareInfo
{
    public int ID {get;set;}
    public string SoftwareName {get;set;}
    public string  Key {get;set;}
    public DateTime Date {get;set;}
}

protected void ButtonSearch_Click(object sender, EventArgs e)
{
    GridView1.DataSource = SortGridView();
    GridView1.DataBind();// <<--- Exception
}


来源:https://stackoverflow.com/questions/8192259/on-data-binding-linq-to-entities-does-not-recognize-the-method-system-string-t

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