Приложение Aspnetboilerplate выдает ошибку времени выполнения при применении сортировки к запросу для объекта ISoftDelete - PullRequest
0 голосов
/ 09 февраля 2020

Я хочу написать службы CRUD для объекта с именем Местоположение . Местоположение имеет составной первичный ключ, поэтому я не смог использовать AsyncCrudAppService и скопировал нужные методы из AsyncCrudAppService.

Когда я использую сервис GetAll без ApplySorting , он работает нормально. Но когда я добавляю сортировку, я получаю эту ошибку времени выполнения:

[35] ОШИБКА BookingSystem.middlewares.HttpGlobalExceptionFilter [(null)] - выражение LINQ 'DbSet .Where (l => __ef_filter__p_0 || ! (((ISoftDelete) l) .IsDeleted)) .OrderByDescending (l => l.Id) 'не может быть переведено. Либо переписать запрос в форме, которую можно перевести, либо явно переключиться на оценку клиента, вставив вызов либо AsEnumerable (), AsAsyncEnumerable (), ToList (), либо ToListAsyn c (). Для получения дополнительной информации см. https://go.microsoft.com/fwlink/?linkid=2101038.

public class Location : IEntity<int>, IPassivable, IFullAudited<User> {
    public int Id { get; set; }
    public int IdLocation { get; set; }         //primary key 0
    public LocationType TypeId { get; set; }    //primary key 1
    public string Name { get; set; }
}

public interface ILocationService : IApplicationService
{
    Task<PagedResultDto<LocationDto>> GetAllAsync(PagedLocationResultRequestDto input);
}

public class LocationService : AbpServiceBase, ILocationService, IPerWebRequestDependency
{
    private readonly IRepository<Location, int> _repository;
    private IAsyncQueryableExecuter AsyncQueryableExecuter { get; set; }

    public LocationService(IRepository<Location> repository)
    {
        _repository = repository;
        AsyncQueryableExecuter = NullAsyncQueryableExecuter.Instance;
    }


    public async Task<PagedResultDto<LocationDto>> GetAllAsync(PagedLocationResultRequestDto input)
    {
        if (input.MaxResultCount > _appSettings.Value.MaxResultCount)
        {
            throw new BookingSystemUserFriendlyException(BookingSystemExceptionCode.InputNotValid,
                nameof(input.MaxResultCount));
        }

        var query = CreateFilteredQuery(input);

        var totalCount = await AsyncQueryableExecuter.CountAsync(query);

        query = ApplySorting(query, input);
        query = ApplyPaging(query, input);

        var entities = await AsyncQueryableExecuter.ToListAsync(query);

        return new PagedResultDto<LocationDto>(
            totalCount,
            entities.Select(MapToEntityDto).ToList()
        );
    }

    protected virtual IQueryable<Location> ApplySorting(
        IQueryable<Location> query, PagedLocationResultRequestDto input)
    {
        if (input is ISortedResultRequest sortInput &&
            !sortInput.Sorting.IsNullOrWhiteSpace())
        {
            return query.OrderBy(sortInput.Sorting);
        }

        return query.OrderByDescending(e => e.Id);
    }

    protected virtual IQueryable<Location> ApplyPaging(
        IQueryable<Location> query, PagedLocationResultRequestDto input)
    {
        if (input is IPagedResultRequest pagedInput)
        {
            return query.PageBy(pagedInput);
        }

        return query;
    }

    private IQueryable<Location> CreateFilteredQuery(PagedLocationResultRequestDto input)
    {
        return _repository.GetAll()
            .WhereIf(!string.IsNullOrWhiteSpace(input.Name),
                location => location.Name.ToLower().Contains(input.Name.Trim().ToLower()));
    }

    private LocationDto MapToEntityDto(Location entity)
    {
        return ObjectMapper.Map<LocationDto>(entity);
    }
}

Версия пакета ABP: 5.1.0

Базовая структура:. Net Core

1 Ответ

1 голос
/ 11 февраля 2020

Ну, я задал тот же вопрос в GitHub проекта и получил ответ. В ApplySorting сортировка по умолчанию основана на Id , которого нет в моей таблице базы данных.

Если вы используете составной PK, то у вас, вероятно, нет поля Id в базе данных, верно? Тогда вам не следует сортировать по Id.

https://github.com/aspnetboilerplate/aspnetboilerplate/issues/5274#issuecomment -583946065

...