使用Expression <func <t>&gt;的SQL查询where where condition

时间:2016-09-21 08:07:25

标签: c# sql-server repository-pattern

在我的项目中,我有三层这样的。

存储库层

IEnumerable<Tag> IRepository<Tag>.GetMany(Expression<Func<Tag, bool>> where)
{
    Expression<Func<Tag, bool>> cat = where; 
    //what to do here with where variable to get the value.

    using (var cmd = DbContext.CreateCommand())
    {
        cmd.CommandText = "Select Id, Name, UrlSlug, Description, DateAdded, UserId from Tag"; // where UserId = @UserId";
        //cmd.AddParameter("@UserId", UserId);
         return ToList(cmd);
     }
 }

服务层代码

public IEnumerable<Category> GetMany(Expression<Func<Category, bool>> where)
{
    return _repository.GetMany(where);
}

在PageLoad事件中调用的方法背后的代码

void BindGrid()
{
   var categories = Service.GetMany(c => c.User.UserId == Guid.Parse(Session["guid"].ToString()));
   gvCategory.DataSource = categories;
   gvCategory.DataBind();
}

现在这个函数正在返回数据库中的所有结果,但是必须只返回记录where userId = @UserId。我希望它只返回与用户相关的行(不是全部)。

请指导我如何实现。我是第一次使用Expression。感谢

0 个答案:

没有答案