繁体   English   中英

实体框架返回 InvalidCastException

[英]Entity Framework returns InvalidCastException

我正在尝试使用 odata v4 和 efcore (.net 5) 进行 groupby 查询,但我遇到了这个错误:

System.InvalidCastException:无法将类型为“Microsoft.EntityFrameworkCore.Query.SqlExpressions.SqlConstantExpression”的 object 转换为类型“System.Linq.Expressions.ConstantExpression”。

    [HttpPost("odata/v1/Infraccion/InfraccionesConsultadas")]
    [EnableQuery]
    public IActionResult InfraccionesConsultadas()
    {
        //_repository.GetAll() returns an IQueryable
        return Ok(_repository.GetAll());
    }

这是带有查询参数的 url

/odata/v1/Infraccion/InfraccionesConsultadas?$apply=compute(year(FechaHora)%20as%20y)/groupby((y))

除此之外,我没有问题,例如,当我过滤时: /odata/v1/Infraccion/InfraccionesConsultadas?$filter=Lugar eq 'TEST'

对可能发生的事情有任何想法吗?

编辑:这是我正在使用的存储库中的父 class

public abstract class BaseRepository<T, TContext> : IRepository<T>, IDisposable where T : Model where TContext : DbContext
    {
        protected readonly TContext _context;

        public BaseRepository(TContext context)
        {
            _context = context;
        }


        public virtual IQueryable<T> GetAll(bool getDeleted = false)
        {
            try
            {
                DbSet<T> source = _context.Set<T>();
                return (!getDeleted) ? source.Where((T item) => item.IsDeleted == false) : source.Select((T item) => item);
            }
            catch (Exception ex)
            {
                throw new Exception("Couldn't retrieve entities: " + ex.Message, ex);
            }
        }

      //...
       
}

这是由于调用了自定义 function 的 IQueryable 结果。

看起来您需要添加 AsEnumerable() 或 ToList()

return Ok(_repository.GetAll().ToList());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM