简体   繁体   中英

How do i use filter in linq against non string fields?

I'm using jquery datatables plugin in my mvc application. filtering works perfectly against the fields with string datatype. but i cant use filtering against non string fields without enumerating the results first. here is my code.

 public  List<MerchAgreementMain> getAgreementbyAccountNo(jQueryDataTableParamModel model)
    {
        var entity = new CCMSEntities();
        var query = (from _first in entity.First
                     from _second in entity.Second
                     where _first.No == _second.No 
        select new MerchAgreementMain
                     {
                         AcctNo = _Account.AcctNo,   // datatype long
                         BusnName = _Account.BusnName,
                         CreatedBy = _Account.CreatedBy,  
                         CreationDate = _Account.CreationDate ?? DateTime.MinValue,  
                         Status = _Reflib.Descp
                     });
        if (model.sSearch != null)
        {
            var x = query.AsEnumerable().Where(p => Convert.ToString(p.AcctNo).Contains(model.sSearch) || p.BusnName.Contains(model.sSearch) || p.CreatedBy.Contains(model.sSearch)||
                p.Status.Contains(model.sSearch));
          this.displayRecods = x.Count();
           return x.ToList();
        }
        //var result = query.ToPagedList(Convert.ToInt16(model.sEcho),Convert.ToInt16(model.iDisplayLength));
        return query.ToList();
    }

this works fine. but the issue is that the query is enumerated first before applying the filters and the database contains thousands of records; that seems to be a bad practice and can take some delay before showing the filtered result. how do i apply the filter in an Iqueryable for long?

Instead of

query.AsEnumerable().Where(....

apply filters directly.

query.Where(

Please see: IQueryable vs. IEnumerable in terms of LINQ to SQL queries

Since you are doing AsEnumerable your query is iterating first and then applying the filter. If you apply the filter without AsEnumerable then the query is IQueryable and it will apply the filters only when iterating over the resultset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM