0
  const string keyword = "manoj";
        rsp.DataSource = company.GetCompanySearch(keyword);
        rsp.DataBind();

    public List<Company> GetCompanySearch(string keyword)
{
    using (var context = huntableEntities.GetEntitiesWithNoLock())
    {
        List<Company> query = context.Companies.ToList();
        if (!string.IsNullOrEmpty(keyword))
        {
            keyword = keyword.ToLower();
            query =  (List<Company>) query.Where(u=>u.CompanyName.Contains(keyword)
                                           || u.EmailAdress.Contains(keyword)
                                           ||u.MasterCountry.Description.Contains(keyword)
                                           ||u.MasterIndustry.Description.Contains(keyword)
                                           ||u.CompanyDescription.Contains(keyword)
                                           ||u.CompanyHeading.Contains(keyword));
        }
        return query.ToList();
    }
}

以下代码引发以下异常:{“无法转换类型为 'WhereListIterator 1[Data.Company]' to type 'System.Collections.Generic.List1[Data.Company]' 的对象。”}

4

1 回答 1

1

“(List)query.Where()”等于“(List)(query.Where())”,所以这将抛出该异常。应该使用 query.Where().ToList() 但不是显式转换。

此外,最好不要输入“List query = context.Companies.ToList();” 在你的“如果”陈述之前。在这种情况下,无论关键字是否为空,它都会将所有记录查询到内存中,这会导致性能问题。可以改成下面

    IQueryable<Company> query = context.Companies; //Remove ToList()
    if (!string.IsNullOrEmpty(keyword))
    {
        keyword = keyword.ToLower();
        // Remove cast
        query =  query.Where(u=>u.CompanyName.Contains(keyword)
                                       || u.EmailAdress.Contains(keyword)
                                       ||u.MasterCountry.Description.Contains(keyword)
                                       ||u.MasterIndustry.Description.Contains(keyword)
                                       ||u.CompanyDescription.Contains(keyword)
                                       ||u.CompanyHeading.Contains(keyword));
    }
    return query.ToList();
于 2012-12-10T06:29:41.497 回答