skip to Main Content

I’m asking this question because I haven’t found any solution. I rewrote my code multiple times by tutorials but nothing changed.

Broken query method in ReadRepository.cs:

public async Task<T> GetByIdAsync(string id) => await Table.FindAsync(Guid.Parse(id));

ShowDraw.cshtml.cs:

private readonly IDrawReadRepository _drawReadRepository;

public ShowDrawModel(IDrawReadRepository drawReadRepository)
{
    _drawReadRepository = drawReadRepository;            
}

public Draw Draw { get; set; }

public async Task OnGet(string id)
{
    Draw = await _drawReadRepository.GetByIdAsync(id);

    if (Draw == null)
    {
        RedirectToPage("../Content/Error/UserNotFound");
    }            
}

CreateDraw.cshtml.cs (sends id after the entity creation to ShowDraw.cshtml.cs):

public async Task<IActionResult> OnPostAsync()
{
    Draw draw;

    if (_signInManager.IsSignedIn(User))
    {
        var user = _userManager.GetUserAsync(User).Result;

        if (user != null)
        {
            draw = CreateDraw(user);
        }
        else
        {
            return RedirectToPage("/Error/UserNotFound");
        }
    }
    else
    {
        draw = CreateDraw(null);
    }

    await _drawWriteRepository.AddAsync(draw);
    await _drawWriteRepository.SaveAsync();

    return RedirectToPage("../User/ShowDraw", new { id = draw.Id.ToString() });
}

After I create an entity, it successfully saves it to the database, but after redirecting to the Show page, it throws this exception:

An unhandled exception occurred while processing the request.
ArgumentException: Expression of type ‘System.Collections.Generic.ICollection1[System.String]' cannot be used for parameter of type 'System.Collections.Generic.IList1[System.String]’ of method ‘System.Collections.Generic.IList1[System.String] PopulateList[String](System.Collections.Generic.IList1[System.String], System.Collections.Generic.IList`1[System.String])’ (Parameter ‘arg0’)
System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, string methodParamName, string argumentParamName, int index)

ArgumentException: Expression of type ‘System.Collections.Generic.ICollection1[System.String]' cannot be used for parameter of type 'System.Collections.Generic.IList1[System.String]’ of method ‘System.Collections.Generic.IList1[System.String] PopulateList[String](System.Collections.Generic.IList1[System.String], System.Collections.Generic.IList`1[System.String])’ (Parameter ‘arg0’)

System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, string methodParamName, string argumentParamName, int index)
System.Linq.Expressions.Expression.Call(MethodInfo method, Expression arg0, Expression arg1)
Microsoft.EntityFrameworkCore.Query.Internal.EntityMaterializerSource.g__CreateMemberAssignment|14_0(Expression parameter, MemberInfo memberInfo, IPropertyBase property, Expression value)
Microsoft.EntityFrameworkCore.Query.Internal.EntityMaterializerSource.AddInitializeExpressions(HashSet properties, ParameterBindingInfo bindingInfo, Expression instanceVariable, List blockExpressions)
Microsoft.EntityFrameworkCore.Query.Internal.EntityMaterializerSource.CreateMaterializeExpression(List blockExpressions, ParameterExpression instanceVariable, Expression constructorExpression, HashSet properties, ParameterBindingInfo bindingInfo)
Microsoft.EntityFrameworkCore.Query.Internal.EntityMaterializerSource.CreateMaterializeExpression(EntityMaterializerSourceParameters parameters, Expression materializationContextExpression)
Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor+EntityMaterializerInjectingExpressionVisitor.CreateFullMaterializeExpression(ITypeBase concreteTypeBase, ValueTuple<Type, ParameterExpression, ParameterExpression, ParameterExpression> materializeExpressionContext)
Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor+EntityMaterializerInjectingExpressionVisitor.MaterializeEntity(StructuralTypeShaperExpression shaper, ParameterExpression materializationContextVariable, ParameterExpression concreteEntityTypeVariable, ParameterExpression instanceVariable, ParameterExpression entryVariable)
Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor+EntityMaterializerInjectingExpressionVisitor.ProcessEntityShaper(StructuralTypeShaperExpression shaper)
Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor+EntityMaterializerInjectingExpressionVisitor.VisitExtension(Expression extensionExpression)
Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor+EntityMaterializerInjectingExpressionVisitor.Inject(Expression expression)
Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.InjectEntityMaterializers(Expression expression)
Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor+ShaperProcessingExpressionVisitor.VisitExtension(Expression extensionExpression)
Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor+ShaperProcessingExpressionVisitor.ProcessShaper(Expression shaperExpression, out RelationalCommandCache relationalCommandCache, out IReadOnlyList readerColumns, out LambdaExpression relatedDataLoaders, ref int collectionId)
Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.VisitShapedQuery(ShapedQueryExpression shapedQueryExpression)
Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.VisitExtension(Expression extensionExpression)
Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.VisitExtension(Expression extensionExpression)
Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor(Expression query)
Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery(Expression query, bool async)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore(IDatabase database, Expression query, IModel model, bool async)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler+<>c__DisplayClass12_0.b__0()
Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery(object cacheKey, Func<Func<QueryContext, TResult>> compiler)
Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync(Expression query, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync(Expression expression, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync<TSource, TResult>(MethodInfo operatorMethodInfo, IQueryable source, Expression expression, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync<TSource, TResult>(MethodInfo operatorMethodInfo, IQueryable source, LambdaExpression expression, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.FirstOrDefaultAsync(IQueryable source, Expression<Func<TSource, bool>> predicate, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Internal.EntityFinder.FindAsync(object[] keyValues, CancellationToken cancellationToken)
Microsoft.EntityFrameworkCore.Internal.InternalDbSet.FindAsync(object[] keyValues)
xxx.Persistence.Repositories.ReadRepository.GetByIdAsync(string id) in ReadRepository.cs
public async Task GetByIdAsync(string id) => await Table.FindAsync(Guid.Parse(id));
xxx.Pages.User.ShowDrawModel.OnGet(string id)

Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory+NonGenericTaskHandlerMethod.Execute(object receiver, object[] arguments)
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

  1. I have tried entity Id type change from Guid to int. (Same result)
  2. I apply at least 3 different repository pattern approaches from tutorials. (Same result)

2

Answers


  1. Chosen as BEST ANSWER

    Here is the solution (Thank you so much Brando Zhang):

    I was using ICollection<string> for property types in my models. It was like;

    public class Draw : Entity
    {
        public ICollection<string> Winners { get; set; }
        public ICollection<string> ReserveWinners { get; set; }
    }
    

    I was getting the listed string data by jQuery. Adding to DB was fine but retrieving the entity from DB throws the exception above.

    I changed the property types to string and use the Split() method to list them when I need them. This solution successfully solved the problem.


  2. As a comment to the answer above (new to the forum and too few points to comment :). I get the same exception in my application, and changing ICollection<string> to IList<string> solves it for me.

    public class Draw : Entity
    {
        public IList<string> Winners { get; set; }
        public IList<string> ReserveWinners { get; set; }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search