将参数传递给Expression <func <tentity,bool =“”>&gt;过滤... </func <tentity,>

时间:2014-12-18 09:17:18

标签: asp.net-mvc generics lambda

我正在使用GenericRepository和这段代码......

        public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

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

        query = includeProperties.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Aggregate(query, (current, includeProperty) => current.Include(includeProperty));

        return orderBy != null ? orderBy(query).ToList() : query.ToList();
    }

我想在我的控制器中使用此功能......

        public ActionResult Hojas_Read([DataSourceRequest] DataSourceRequest request)
    {
        var usuario = _utHojas.UsuariosRepository.Get(u => u.Correo == User.Identity.Name).FirstOrDefault();
        ..... 
    }

但是,这不起作用,因为参数User.Identity.Name没有转换它.... 我该怎么办?

1 个答案:

答案 0 :(得分:0)

我回答自己......

      var name = User.Identity.Name;
      ParameterExpression param = Expression.Parameter(typeof (Usuario), "h");
      Expression boby = Expression.Equal(Expression.PropertyOrField(param, "Correo"),
            Expression.Constant(name, typeof(string)));
      Expression<Func<Usuario, bool>> filter = Expression.Lambda<Func<Usuario, bool>>(boby, param);

      var usuario = _utHojas.UsuariosRepository.Get(filter).FirstOrDefault();