构建一个定制|在LINQ查询进步? [英] Building a custom|progressive query in LINQ?

查看:164
本文介绍了构建一个定制|在LINQ查询进步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有五个文本框的页面时,每一个重$ P $在我的数据库表和一个搜索按钮psenting字段:

如果我是使用SQL我可以建立我的SQL语句,这取决于域在他们的数据。

不过,我想使用LINQ和我在一个不知如何做到这一点。例如,看看下面的查询:

 变种DB =新BookDBDataContext();        变种Q =
            从在db.Books
            其中,a.Title.Contains(txtBookTitle)及&放大器;
                  a.Author.Contains(txtAuthor)及&放大器;
                  a.Publisher.Contains(txtPublisher)
            选择a.ID;

上面的查询将返回,所有的字段匹配表数据。但是,如果用户没有输入什么在txtAuthor领域的作者?如果我建立这个作为查询字符串,我可以检查每个字段的数据,并将其添加到查询字符串。由于这是LINQ,我不能动态地改变搜索条件,它似乎。

任何意见将是极大的AP preciate!


解决方案

 变种DB =新BookDBDataContext(); 在db.Books变种Q =(从
          其中,a.Title.Contains(txtBookTitle)); 如果(!String.IsNullOrEmpty(txtAuthor))
 {
      Q = q.Where(一个= GT; a.Author.Contains(txtAuthor));
 }
 如果(!String.IsNullOrEmpty(txtAuthor))
 {
      Q = q.Where(一个= GT; a.Publisher.Contains(txtPublisher));
 } 变种的id = q.Select(一个= GT; a.ID);

I have a page with five text boxes, each one representing a field in my database table and a search button:

If I were using SQL I could build my SQL statement depending on which fields have data in them.

However, I want to use LINQ, and I'm at a loss as to how to accomplish this. For instance, take a look at the query below:

        var db = new BookDBDataContext();

        var q =
            from a in db.Books
            where a.Title.Contains(txtBookTitle) &&
                  a.Author.Contains(txtAuthor) &&
                  a.Publisher.Contains(txtPublisher)
            select a.ID;

The query above will return data where all the fields match data in the table. But, what if the user didn't enter an Author in the txtAuthor field? If I were building this as a query string, I could check each field for data and add it to the query string. Since this is LINQ, I can't dynamically change the search criteria, it seems.

Any advice would be greatly appreciate!

解决方案

 var db = new BookDBDataContext();

 var q = (from a in db.Books
          where a.Title.Contains(txtBookTitle));

 if(!String.IsNullOrEmpty(txtAuthor)) 
 {
      q = q.Where(a => a.Author.Contains(txtAuthor));
 }


 if(!String.IsNullOrEmpty(txtAuthor)) 
 {
      q = q.Where(a => a.Publisher.Contains(txtPublisher));
 }

 var id = q.Select(a => a.ID);

这篇关于构建一个定制|在LINQ查询进步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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