在通用存储库中使用表达式选择

时间:2018-09-29 11:19:39

标签: asp.net entity-framework

我有一个通用存储库,具有这样的方法

   public async Task<List<TEntity>> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, Expression<Func<TEntity, TEntity>> select=null)
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        if (select != null)
        {
            query = query.Select(select);
        }
        if (orderBy != null)
        {
            return await orderBy(query).ToListAsync();
        }
        else
        {
            return await query.ToListAsync();
        }
    }

并像这样在我的存储库中使用它:

return await _unitOfWork.GetRepository<DeliveryMethod>().
                Get(q => q.DeliveryMethodLoclizes.Any(x => x.LanguageId == language), null,
                    s => new DeliveryMethod()
                    {
                        Id = s.Id,
                        IsActive = s.IsActive,
                        IsDel = s.IsDel,
                        DeliveryMethodLoclizes = s.DeliveryMethodLoclizes.Where(x => x.LanguageId == language)
                            .Select(w => new DeliveryMethodLocalize()
                            {
                                Id = w.Id,
                                LanguageId = w.LanguageId,
                                Title = w.Title,
                                Description = w.Description
                            })
                            .ToList()
                    });

但是当我运行代码时,会向我返回此错误

The entity or complex type 'Domain.DeliveryMethod' cannot be constructed in a LINQ to Entities query.

请帮助我解决此错误

1 个答案:

答案 0 :(得分:0)

这是设计使然,EF不允许您将查询结果投影到映射的实体上。您可以使用不从映射实体继承的DTO或匿名类型