如何将简单的视图模型转换为Func< T,bool>谓词? [英] How to convert a simple viewmodel to Func<T,bool> predicate?

查看:73
本文介绍了如何将简单的视图模型转换为Func< T,bool>谓词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Person View Model

public class PersonViewModel
{
    public int ID {get;set;}
    public String FirstName {get;set;}
    public String LastName {get;set;}
}

该视图具有三个字段

我的PersonService中具有此功能,该功能使用被注入的EF6数据上下文.

I have this function in my PersonService which uses an EF6 datacontext which gets injected.

 public IQueryable<Person> Search(Expression<Func<Person,bool>> predicate)
        {
            return dataContext.GetSet<Person>().Where(predicate);
        }

现在我的MVC控制器实际上可以与PersonViewModel class

Now my MVC Controller actually works with a PersonViewModel class

[HttpPost]
public ActionResult Search(PeopleSearchViewModel model)
{
      if (ModelState.IsValid)
            {
                var listOfPersons= PersonService.Search(
                   //map viewmodel to model and search here)

                //return the list and render a view etc...not important
            }
        }

所以我想知道的是,如果我能以某种方式采用PersonViewModel,创建一个Func<Person,bool>谓词并将其传递给PersonService进行搜索,而不是使用自动映射器将我的视图模型映射到它,是否是一个好主意?域模型?

So what I am wondering is whether it is a good idea if I can somehow take the PersonViewModel, create a Func<Person,bool> predicate and pass it to the PersonService for search, instead of using automapper to map my view model to domain model ?

谢谢

推荐答案

首先,您将Func类型作为谓词传递给返回IQueryable的函数.实际上,您应该传递Expression<Func<Person, bool>>,以便生成查询的任何人都可以将函数实际检查为表达式树并从中生成SQL或其他内容.如果您不这样做,查询生成器可能最终会加载整个表并手动进行迭代(这种情况在实体框架中看到一次).

Firstly, you are passing type Func as the predicate to a function returning an IQueryable. You should actually be passing in an Expression<Func<Person, bool>> so that whatever generates your query can actually inspect the function as an expression tree and generate SQL or something from it. If you don't, your query generator may end up loading your entire table and iterating manually (saw this happen with entity framework once).

回答您的问题:我会在您的PeopleSearchViewModel上创建一个函数,如下所示:

On to your answer: I would make a function on your PeopleSearchViewModel like so:

public Expression<Func<Person, bool>> ToExpression()
{
    //this can be whatever your search query needs to be... I just did this quick and dirty
    return p => p.FirstName == this.FirstName || p.LastName == this.LastName  || p.ID == this.ID;
}

然后,只需将调用model.ToExpression()的结果传递给搜索函数即可.

Then, simply pass the result of calling model.ToExpression() in to your search function.

这篇关于如何将简单的视图模型转换为Func&lt; T,bool&gt;谓词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆