System.NotSupportedException:' LINQ表达式节点类型' Invoke' LINQ to Entities不支持。'

时间:2017-06-25 15:02:22

标签: c# entity-framework linq

任何人都可以帮我解决这个错误吗?这是我的代码:

    private void loadList(IQueryable<customer> customers)
    {
        ListView.Items.Clear();
        foreach (var customer in customers)
        {
            ListViewItem item = new ListViewItem(customer.customerNumber.ToString());
            item.SubItems.Add(customer.customerName);
            item.SubItems.Add(customer.contactFirstName);
            item.SubItems.Add(customer.contactLastName);
            item.SubItems.Add(customer.phone);
            item.SubItems.Add(customer.addressLine1);
            item.SubItems.Add(customer.addressLine2);
            item.SubItems.Add(customer.city);
            item.SubItems.Add(customer.state);
            item.SubItems.Add(customer.postalCode);
            item.SubItems.Add(customer.country);
            item.SubItems.Add(customer.salesRepEmployeeNumber.ToString());
            item.SubItems.Add(customer.creditLimit.ToString());

            ListView.Items.AddRange(new ListViewItem[] { item });
        }
    }

    private static readonly Func<customer, string>[] _searches;

    static Main()
    {
        _searches = new Func<customer, string>[]
        {
            (c) => c.customerNumber.ToString(),
            (c) => c.customerName,
            (c) => c.contactFirstName,
            (c) => c.contactLastName,
            (c) => c.phone,
            (c) => c.addressLine1,
            (c) => c.addressLine2,
            (c) => c.city,
            (c) => c.state,
            (c) => c.postalCode,
            (c) => c.country,
            (c) => c.salesRepEmployeeNumber.ToString(),
            (c) => c.creditLimit.ToString(),
        };
    }

    protected virtual void SearchBox_TextChanged(object sender, EventArgs e)
    {

        var search = _searches[SearchItem.SelectedIndex];

        CustomerContext context = new CustomerContext();

        IQueryable<customer> customers = from x in context.customers
                                         where search(x).Contains(SearchBox.Text)
                                         select x;

        loadList(customers);

    }

我在foreach开头的loadList方法中得到了这个错误:

  

&#39; LINQ表达式节点类型&#39;调用&#39; LINQ to Entities不支持。&#39;

我该如何解决这个问题? 我对这一切都很陌生,我尝试过几件事,但都没有。

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

答案在haim770的评论中给出,但似乎你仍然有一些麻烦,所以我会稍微扩展一下。首先安装LinqKit nuget包。然后将搜索列表更改为包含表达式而不是委托:

private static readonly Expression<Func<customer, string>>[] _searches;

然后按如下方式更改搜索方法(添加using LinqKit):

IQueryable<customer> customers = from x in context.customers.AsExpandable()
                                 where search.Invoke(x).Contains(SearchBox.Text)
                                 select x;