在数据绑定上:LINQ to Entities不能识别方法'System.String ToString()'方法 [英] On data binding: LINQ to Entities does not recognize the method 'System.String ToString()' method

查看:136
本文介绍了在数据绑定上:LINQ to Entities不能识别方法'System.String ToString()'方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 LINQ to Entities



我的GridView如下:

 < asp:GridView ID =GridView1runat =serverAutoGenerateColumns =FalseAllowPaging =True
EmptyDataText = NoDataCellPadding =3CellSpacing =1
AllowSorting =TrueOnPageIndexChanging =GridView1_PageIndexChangingOnRowCancelingEdit =GridView1_RowCancelingEdit
OnRowEditing =GridView1_RowEditingOnRowUpdating =GridView1_RowUpdatingCssClass =gridview
OnSorting =GridView1_SortingHorizo​​ntalAlign =Center>
< AlternatingRowStyle BackColor =#F0F0F0/>
<列>
< asp:BoundField HeaderText =IDDataField =IDReadOnly =TrueSortExpression =ID/>
< asp:BoundField HeaderText =NameDataField =SoftwareNameSortExpression =Name/>
< asp:BoundField HeaderText =KeyDataField =KeySortExpression =Key/>
< asp:BoundField HeaderText =DateDataField =DateItemStyle-CssClass =date_tdSortExpression =Date
ReadOnly =True>
< ItemStyle CssClass =date_td>< / ItemStyle>
< / asp:BoundField>
< asp:TemplateField>
< ItemTemplate>
< asp:ImageButton runat =serverToolTip =editID =EditButtonCommandName =Edit
ImageUrl =〜/ images / edit.png/>
< / ItemTemplate>
< EditItemTemplate>
< asp:ImageButton runat =serverID =UpdateButtonToolTip =SubmitCommandName =Update
ImageUrl =〜/ images / ok.gif/>
< asp:ImageButton runat =serverID =CancelToolTip =SubmitCommandName =Cancel
ImageUrl =〜/ images / cancel.gif/>
< / EditItemTemplate>
< / asp:TemplateField>
< asp:TemplateField>
< ItemTemplate>
< asp:ImageButton runat =serverToolTip =DeleteID =btnDeleteCommandName =cDelete
ImageUrl =〜/ images / delete.pngOnCommand =OnDeleteCommandArgument ='<%#绑定(id)%>'
OnClientClick =return confirm('Are you sure?')/>
< / ItemTemplate>
< / asp:TemplateField>
< /列>
< / asp:GridView>

使用以下c#代码填充GridView:

  private IQueryable SortGridView()
{
IQueryable< Softwares>软件=搜索();

if(softwares == null)return null;

string sortExpression =(ViewState [SortExpression] as string)== null
? ID
:ViewState [SortExpression]作为字符串;
string lastDirection =(ViewState [SortDirection] as string)== null
? ASC
:ViewState [SortDirection]作为字符串;

switch(sortExpression)
{
caseID:
softwares =(lastDirection ==ASC)
?软件.OrderBy(q => q.id)
:softwares.OrderByDescending(q => q.id);
休息;

caseName:
softwares = lastDirection ==ASC
? (q => q.softwareName)
:softwares.OrderByDescending(q => q.softwareName);
休息;

caseKey:
softwares =(lastDirection ==ASC)
? (q => q.Keys.Key)
:softwares.OrderByDescending(q => q.Keys.Key);
休息;

案例日期:
软件= lastDirection ==ASC
?软件.OrderBy(q => q.Date)
:softwares.OrderByDescending(q => q.Date);
休息;
}

软件返回q
选择新
{
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(); //<<< - 例外
}

但是在 ButtonSearch_Click 中,我得到以下异常: b


<实体无法识别方法'System.String ToString()'方法,并且此方法无法转换为商店表达式

I LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询语句LINQ to Entities查询在内部转换为sql语句。就你的情况而言,LINQ to Entity provider无法将toString调用映射到合适的SQL语句中。您可以从LINQ中将数据检索到实体,然后枚举离线并进行必要的更改,即:

pre $ var data =(from q在软件中
选择新的
{
ID = q.id,
SoftwareName = q.softwareName,
Key = q.Keys.Key
Date = q.Date
})。ToList();

,然后通过离线调用ToString()方法转换日期部分。

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

您从方法中返回匿名类型。匿名类型只能在定义它们的类中访问。您可以尝试类似下面给出的代码:

  private IList< SoftwareInfo> SortGridView()
{
//常规代码

返回(从软件中的q
中选择新的SoftwareInfo
{
ID = q。 id,
SoftwareName = q.softwareName,
Key = q.Keys.Key,
Date = q.Date
})。ToList();


$ b $ 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(); //<<< - 例外
}


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?

解决方案

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
}

这篇关于在数据绑定上:LINQ to Entities不能识别方法'System.String ToString()'方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆