具有多个左外部联接的Linq查询失败

时间:2020-04-14 10:59:12

标签: c# sql-server linq

我正在构建一个应用程序,用户可以在其中发布问题并支持/反对其他人的问题。我的mssql数据库中有三个表-QuestionsUsersQuestionVotes

Questions表具有列IdAuthorIdTitleContentUpvotesReplies列。
Users表具有列IdAuthorizationIdFirstNameLastName列。
QuestionVotes表具有列IdQuestionIdUserIdUpvoteDownvote列。 -此表中的条目指示UserId给出的用户是否赞成或反对QuestionId给出的问题。

当用户登录到应用程序时,他们应该能够看到自己和其他人发布的问题列表,每个问题的一些作者信息,以及当前用户以前是否曾对问题进行过表决。要获取此信息,我具有以下功能:

public async Task<IEnumerable<QuestionWithAuthorInfo>> GetAllQuestionsWithAuthorInfo(long? currentUserId)
{
    var query = from question in Context.Set<Question>()
                join user in Context.Set<User>()
                on question.AuthorId equals user.Id into us
                from u in us.DefaultIfEmpty()
                join vote in Context.Set<QuestionVote>()
                on question.Id equals vote.QuestionId into vs
                from v in vs.Where(k =>currentUserId != null && k.UserId == currentUserId).DefaultIfEmpty()
                select new QuestionWithAuthorInfo
                {
                    Id = question.Id,
                    Title = question.Title,
                    Content = question.Content,
                    Upvotes = question.Upvotes,
                    Replies = question.Replies,
                    Author = u == null ? null : new AuthorInfo
                    {
                        Id = u.Id,
                        FirstName = u.FirstName,
                        LastName = u.LastName
                    },
                    UserUpvoted = v == null ? false : v.Upvote,
                    UserDownvoted = v == null ? false : v.Downvote
                };
    var result = await query.ToListAsync();
    return result;
}

currentUserId可能为空-这是当前用户尚未发布任何问题或未对任何问题进行投票的时候。在这种情况下,UserUpvotedUserDownvoted的预期结果都是false

但是查询失败,并显示以下错误消息:

Exception has occurred: CLR/System.InvalidOperationException
Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll: 'Processing of the LINQ expression 'DbSet<Question>
    .LeftJoin(
        outer: DbSet<User>
            .AsQueryable(), 
        inner: question => question.AuthorId, 
        outerKeySelector: user => (Nullable<long>)user.Id, 
        innerKeySelector: (question, u) => new { 
            <>h__TransparentIdentifier0 = new { 
                question = question, 
                us = us
             }, 
            u = u
         })
    .GroupJoin(
        outer: DbSet<QuestionVote>, 
        inner: <>h__TransparentIdentifier1 => <>h__TransparentIdentifier1.<>h__TransparentIdentifier0.question.Id, 
        outerKeySelector: vote => vote.QuestionId, 
        innerKeySelector: (<>h__TransparentIdentifier1, vs) => new { 
            <>h__TransparentIdentifier1 = <>h__TransparentIdentifier1, 
            vs = vs
         })' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information.'
   at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.Expand(Expression query)
   at Microsoft.EntityFrameworkCore.Query.QueryTranslationPreprocessor.Process(Expression query)
   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__DisplayClass12_0`1.<ExecuteAsync>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToListAsync>d__64`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at API.Repositories.Concrete.QuestionRepository.<GetAllQuestionsWithAuthorInfo>d__4.MoveNext()

我该如何解决这个问题? 谢谢。

0 个答案:

没有答案