Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query By SubProperty #10

Closed
luizfbicalho opened this issue Oct 29, 2019 · 4 comments
Closed

Query By SubProperty #10

luizfbicalho opened this issue Oct 29, 2019 · 4 comments

Comments

@luizfbicalho
Copy link

I created this two classes

`

public class Child
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    [DataType("varchar")]
    public string Description { get; set; }

    public virtual Parent Parent { get; set; }
}`

And

`

 public class Parent
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    [DataType("varchar")]
    public string Description { get; set; }
}`

and created a controller with two methods

`

    [HttpGet("Grid")]
    public IActionResult Grid()
    {
        try
        {
            var result = Context.Children.AsQueryable().ToDataSourceResult(999, 0, new List<Sort>(), new Filter
            {
                Filters = new Filter[] { new Filter { Field = "Description", Operator = "contains",
                    Value = "4" } },
                Logic = "and"
            });
            return Ok(result);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }
    [HttpGet("GridParent")]
    public IActionResult GridParent( )
    {
        try
        {
            var result = Context.Children.Include(x=>x.Parent).AsQueryable().ToDataSourceResult(999, 0, new List<Sort>(), new Filter
            {
                Filters = new Filter[] { new Filter { Field = "Parent.Description", Operator = "contains",
                    Value = "4" } },
                Logic = "and"
            });
            return Ok(result);
        }catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

`

The first method works fine but in the second I get the Error
No 'parent' is in scope

How can I make this kind of filter to work?

@linmasaki
Copy link
Owner

I tested the code that you provided and then took no errors in my scenario. So give me a little time to find the error reason and upload a sample to you. Thanks for your response.

@AllanVini47
Copy link

AllanVini47 commented Nov 7, 2019

I have the same problem.

error:

`

System.InvalidOperationException: The LINQ expression 'Where<TransparentIdentifier<IndicadorUnidade, Unidade>>(
source: Join<IndicadorUnidade, Unidade, Nullable, TransparentIdentifier<IndicadorUnidade, Unidade>>(
outer: DbSet,
inner: DbSet,
outerKeySelector: (i) => Property<Nullable>(i, "UnidadeId"),
innerKeySelector: (u) => Property<Nullable>(u, "Id"),
resultSelector: (o, i) => new TransparentIdentifier<IndicadorUnidade, Unidade>(
Outer = o,
Inner = i
)),
predicate: (i) => i.Inner.Descricao != null && i.Inner.Descricao.ToString().Contains("2"))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.g__CheckTranslated|8_0(ShapedQueryExpression translated, <>c__DisplayClass8_0& )
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_01.<Execute>b__0() at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Kendo.DynamicLinqCore.QueryableExtensions.ToDataSourceResult[T](IQueryable1 queryable, Int32 take, Int32 skip, IEnumerable1 sort, Filter filter, IEnumerable1 aggregates, IEnumerable1 group)
at Kendo.DynamicLinqCore.KendoAsyncExtensions.ToDataSourceResultAsync[T](IQueryable1 queryable, DataSourceRequest request) at MC.EntityFramework.DefaultImpl.Repository.AsyncRepository1.OnQueryScalarAsync[T](Task1 queryable, CancellationToken ct) at MC.Interfaces.Repository.BaseAsyncRepository1.QueryScalarAsync[T](Expression1 expression, IUserContext userContext, CancellationToken ct) at MC.AspNetCore.Controllers.CrudController1.PostGrid(DataSourceRequest request, CancellationToken ct)
at lambda_method(Closure , Object )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

`

@linmasaki
Copy link
Owner

linmasaki commented Feb 12, 2020

@luizfbicalho @AllanVini47

Please upgrade the package to version v3.1.0. I also add NUnit test cases for you to check(See FilterTest.cs)!

@luizfbicalho
Copy link
Author

Thanks @linmasaki I'll try it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants