Help with linq query RRS feed

  • Question

  • Hello. I have this code

    public IEnumerable<UrlAd> GetUniqueIds(IEnumerable<UrlAd> urlAds) { IEnumerable<UrlAd> result=null; if (urlAds != null && urlAds.Count() > 0) { using (var db = context.GetContext()) { var entity = db.Set<UrlAd>(); result = urlAds.Where(x =>! entity.Any(w => x.BoardId == w.BoardId && x.InnerId == w.InnerId)).ToList(); } } return result; }

    But it's code do a lot of query to DB. I want to one query. What can I change?


    Sunday, January 26, 2014 4:30 PM


  • Hello,

    >>But it's code do a lot of query to DB. I want to one query. What can I change?

    Do you use .ToList() or other similar method to load data to local? When these method is executed, it will query the database once.

    For achieving what you want, we can use the IQueryable<T> type as below:

    using (DataBaseFirstDBEntities db = new DataBaseFirstDBEntities())
                    IQueryable<Order> orderList = db.Orders.AsQueryable();
                    IQueryable<Order> result = null;
                    if (orderList != null && orderList.Count() > 0)
                        var Orders = db.Set<Order>().Where(o => o.OrderID == 1);
                        result = orderList.Where(ol => !Orders.Any(o => ol.OrderID == o.OrderID)).AsQueryable();

    It will query the database one time.

    Note: Please put the codes under one context object.

    The difference between ToList and IQueryable:

    IQueryable extends IEnumerable. Both do not project/inflate their data until being iterated, whereas IList objects pull all their data and are populated when assigned to.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, January 27, 2014 6:13 AM