在EF Core中选择性能问题

时间:2016-12-30 20:45:44

标签: entity-framework entity-framework-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);

您好,我想知道如何更好地更改我的选择查询?

此代码如下所示,看起来很乱。 首先执行任何,如果是真的,请获取最后一个。但是还有更短的代码吗?

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

我试过没有任何(),如果没有数据,它会将错误视为空对象。

请帮帮我。

谢谢:)

1 个答案:

答案 0 :(得分:0)

使用此

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

此外,您可以在上下文配置中禁用此查询的延迟加载

context.Configuration.LazyLoadingEnabled = false; 

通过这种方式,您可以消除Include方法,导致语句缩短但性能不佳。使用存储过程来提高性能。 Stored Procedure in Entity Framework