MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.29k stars 327 forks source link

Mapster.EFCore ProjectToType<T>().SingleOrDefault throwing exception #566

Closed MortenRickiRasmussen closed 1 year ago

MortenRickiRasmussen commented 1 year ago

Hi!

I have this piece of code

public async Task<T> SingleOrDefault(int id) 
{
  var query = DbContext.SomeEntity.Where(x => x.Id == id);

   return await _mapper.From(query).ProjectToType<T>().SingleOrDefaultAsync();
}

it throws the following Exception

Data: System.MissingMethodException: Constructor on type 'Mapster.EFCore.MapsterAsyncEnumerable`1[[SomeSystem.SomeDto, SomeSystem.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' not found.
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
   at Mapster.EFCore.MapsterQueryableProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.SingleOrDefaultAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken) .........

If i exchange the code to the following, it works fine

public async Task<T> SingleOrDefault(int id) 
{
   var query = DbContext.SomeEntity.Where(x => x.Id == id);

   var list = await _mapper.From(query).ProjectToType<T>().ToListAsync();

   return list.FirstOrDefault();
}

Additional info:

AspNet 7.0 Mapster 7.3.0 Mapster.EFCore 5.1.0

andrerav commented 1 year ago

Have you tried materializing the list before calling ProjectToType()? There are some issues when using ProjectToType with async queries.

andrerav commented 1 year ago

Assuming this was solved by materializing the query first.

SeiOkami commented 11 months ago

Looks like a bug

image