简体   繁体   中英

Select performance problems in EF Core

        _context.Homestays   
                .Include(x => x.CreatedUser)
                .Include(x => x.UpdatedUser)
                .Include(x => x.HomestayEvaluations)
                .Include(x => x.HomestayContracts)
                .Include(x => x.HomestayPoliceChecks)
                .Include(x => x.HomestayHouseHolds)
                .AsNoTracking()
                .Select(x => new Homestay()
                {
                    HomestayId = x.HomestayId,
                    HomestayFamily = ConstValue.GetHomestayFamilyName(x),
                    Address = x.Address,
                    Score = x.HomestayEvaluations.Any(x1 => x1.IsEvaluationActive) ? x.HomestayEvaluations.LastOrDefault(x1 => x1.IsEvaluationActive).GetScore() : 0,
                    Contract = x.HomestayContracts.Any(x1 => x1.IsContractActive) ? x.HomestayContracts.LastOrDefault(x1 => x1.IsContractActive).ContractDate : null,
                    Students = x.Students,
                    HouseHolders = x.HomestayHouseHolds.Count(x1 => x1.IsHouseHoldActive),
                    PoliceCheck = x.HomestayPoliceChecks.Any(x1 => x1.IsPoliceCheckActive) ? x.HomestayPoliceChecks.LastOrDefault(x1 => x1.IsPoliceCheckActive).PoliceCheckDate : null,
                    Language = x.Language,
                    Room = x.Room,
                    IsActive = x.IsActive,
                    CreatedDate = x.CreatedDate,
                    CreatedUserName = ConstValue.GetUserName(x.CreatedUser),
                    UpdatedDate = x.UpdatedDate,
                    UpdatedUserName = ConstValue.GetUserName(x.UpdatedUser)
                })
                .OrderByDescending(x => x.HomestayId);

Hello, Im wonder that how do I change my select query better ?

This code as below that it looks messy. first excute any and if it is true, get last one. but is there any more short code ??

Contract = x.HomestayContracts.Any(x1 => x1.IsContractActive) ? x.HomestayContracts.LastOrDefault(x1 => x1.IsContractActive).ContractDate : null

I tried without any(), it occred error as null object if there is no data.

Please help me.

Thanks :)

Use this

Contract = x.HomestayContracts.LastOrDefault(x1 => x1.IsContractActive)?.ContractDate ?? null

Also you can disable lazy loading for this query in context's configuration

context.Configuration.LazyLoadingEnabled = false; 

This way you can eliminate Include methods, cause shorter statement but not better performance. Use stored procedure for performance. Stored Procedure in Entity Framework

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