2017年12月6日 星期三

How to get the all collection of sub-collection latest record

Environment
- .Net Framework 4.6.1
- EF 6.1.3
- Ms Visual Studio 2015

Table

Expected Result


Code
static public IEnumerable<History> GetAllLatestHistoryGroupedByUser(bool includedChild = false)
        {
            var predicate = PredicateBuilder.New<History>();

            if (includedChild)
            {
                predicate = predicate.And(c => c.IsDeleted == false);

                return dataContext.Historys.AsExpandable()
                                           .Where(predicate)
                                           .Include(c => c.User)
                                           .AsEnumerable()
                                           .GroupBy(c => c.userid)
                                           .Select(grp => grp.OrderByDescending(x => x.createdOn).FirstOrDefault());
            }
            else
            {
                return dataContext.Historys.AsExpandable()
                                           .Where(predicate)                                            
                                           .GroupBy(c => c.userid)
                                           .Select(grp => grp.OrderByDescending(x => x.createdOn).FirstOrDefault());
            }
        }            

*** Important Note ***
for include sub-collection, using .Include()

but very important that if any operation after .Include() such as .GroupBy(), .Select()
.Include() will negligible
So it need to add .AsEnumerable() before any operation

沒有留言:

張貼留言