public async Task <UserView> Handle(UserViewBy query) { var queryable = _entities.Query <User>(); if (query.Id.HasValue) { queryable = queryable.Where(EntityExtensions.ById <User>(query.Id.Value)); } else if (query.Principal != null && query.Principal.Identity.IsAuthenticated) { queryable = queryable.Where(EntityExtensions.ById <User>(query.Principal.Identity.GetUserId <int>())); } else { queryable = queryable.Where(QueryUsers.ByName(query.Name)); } // project before querying to only get the data needed for the view. var projection = await queryable.Select(x => new { UserId = x.Id, UserName = x.Name, PrimaryEmailAddress = x.EmailAddresses.Where(y => y.IsPrimary) .Select(y => new { y.Value, y.HashedValue, }) .FirstOrDefault(), }) .SingleOrDefaultAsync().ConfigureAwait(false); if (projection == null) { return(null); } var view = new UserView { UserId = projection.UserId, UserName = projection.UserName, PrimaryEmailAddress = projection.PrimaryEmailAddress.Value, PrimaryEmailHash = projection.PrimaryEmailAddress.HashedValue, }; return(view); }