Search code examples
c#entity-framework-core.net-7.0ef-core-7.0

Typecasting issue when using EF.CompileAsyncQuery with Func in C# for returning nullable type


I'm encountering a typecasting error while using EF.CompileAsyncQuery to define a function that should return a nullable type (Memo?). The code snippet I'm working with is as follows:

public static readonly Func<AppDbContext, int, int, CancellationToken, Task<Memo?>> GetDataByIdAsync =
    EF.CompileAsyncQuery((AppDbContext appDbContext, int memoId, int Id, CancellationToken cancellationToken) =>
         appDbContext.Set<Memo>()
            .Include(d => d.FocusAreas)
            .FirstOrDefaultAsync(d => d.MemoId == memoId && d.CreateUserId == Id, cancellationToken)
    );

The error I'm encountering is:

Cannot implicitly convert type 'System.Func<Infrastructure.Data.AppDbContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task<System.Threading.Tasks.Task<Infrastructure.Entities.Memo>>>' to 'System.Func<Infrastructure.Data.AppDbContext, int, int, System.Threading.CancellationToken, System.Threading.Tasks.Task<Infrastructure.Entities.Memo?>>'

I'm unsure about how to resolve this issue. How can I modify the code to ensure that the returned type aligns with the nullable Memo? type?

Can anyone please help me here by providing their guidance


Solution

  • Use the non-async version of the materialization operation:

    public static readonly Func<AppDbContext, int, int, CancellationToken, Task<Memo?>> GetDataByIdAsync =
        EF.CompileAsyncQuery((AppDbContext appDbContext, int memoId, int Id, CancellationToken _) =>
          appDbContext.Set<Memo>()
            .Include(d => d.FocusAreas)
            .FirstOrDefault(d => d.MemoId == memoId && d.CreateUserId == Id));
    

    The EF.CompileAsyncQuery overloads accept a Expression<Func<..., TResult>> for queryExpression, not Expression<Func<..., Task<TResult>>>