问题
This is the method in my generic repository:
public async Task<TEntity> GetByCondition(Expression<Func<TEntity, bool>> predicate, Func<DbSet<TEntity>, IQueryable<TEntity>> baseQuery = null)
{
IQueryable<TEntity> q = _context.Set<TEntity>();
if (baseQuery != null)
{
q = baseQuery(_context.Set<TEntity>());
}
return await q.Where(predicate).FirstOrDefaultAsync();
}
This is the usage in my business logic:
Expression<Func<Countries, bool>> whereExpr = x => x.SlugHebrew == slug || x.SlugEnglish == slug || x.SlugSpanish == slug;
IQueryable<Countries> BaseQuery(DbSet<Countries> x) => x.Include(z => z.Cities).ThenInclude(b => b.Businesses).ThenInclude(ca => ca.Category)
.Include(z => z.Cities).ThenInclude(b => b.Businesses).ThenInclude(bd => bd.BusinessDetails)
.Include(z => z.Facts)
.Include(z => z.Cities).ThenInclude(a => a.Attractions).ThenInclude(ad => ad.AttractionDetails)
.Include(z => z.Cities).ThenInclude(c => c.HotPlaces)
.Include(z => z.Cities).ThenInclude(z => z.CityImages).ThenInclude(z => z.Image).ThenInclude(z => z.InverseParent)
.Include(z => z.CountryImages).ThenInclude(z => z.Image.InverseParent)
.Select(c=> new Countries
{
CountryImages = c.CountryImages.Where(ci => ci.Image.ParentId == null && ci.Status == (int)EnumGringo.LU_Status.active)
.ToList()
});
Countries country = await _countryRepository.GetByCondition(whereExpr, BaseQuery);
Without the projection it works, but with it I get this error:
ArgumentException: Expression of type 'System.Collections.Generic.IAsyncEnumerable`1[DAL.Models.CountryImages]' cannot be used for parameter of type 'System.Collections.Generic.IEnumerable`1[DAL.Models.CountryImages]' of method 'System.Collections.Generic.List`1[DAL.Models.CountryImages] ToList[CountryImages](System.Collections.Generic.IEnumerable`1[DAL.Models.CountryImages])'
Parameter name: arg0
System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, string methodParamName, string argumentParamName, int index)
This is the Domain model for the Countries Entity:
public partial class Countries
{
public Countries()
{
CountryImages = new HashSet<CountryImages>();
}
public int Id { get; set; }
public virtual ICollection<CountryImages> CountryImages { get; set; }
}
And the CountryImages Model:
public partial class CountryImages
{
public int Id { get; set; }
public int CountryId { get; set; }
public int ImageId { get; set; }
public virtual Countries Country { get; set; }
public virtual UserImages Image { get; set; }
}
来源:https://stackoverflow.com/questions/61698796/ef-core-2-2-cannot-project-while-using-iqueryable