【问题标题】:Linq-C# Query For Dynamic Search Page动态搜索页面的 Linq-C# 查询
【发布时间】:2016-03-30 22:00:01
【问题描述】:

以下是我使用实体框架上下文查询 SQL Server 的原始代码。它查询数据库并使用 StartsWith 方法来匹配用户客户端输入的字符串。这允许用户输入三个字段(FirstName、LastName 和 HOHUPI)的任意组合。

 var results = db.APPLICANTs.Where(p => (p.RESP_FRST.StartsWith(model.FirstName) || model.FirstName == null)
                && (p.RESP_LST.StartsWith(model.LastName) || model.LastName == null) && (p.HOH_UPI.ToString().StartsWith(model.HOHUPI) || model.HOHUPI == null))
                .OrderBy(p => p.RESP_FRST);

此查询仅查看 1 个表(申请人)。但是,我需要将另一个表 (Contact_Info) 包含在结果中。我在 EF 模型中没有导航属性。

我尝试了以下方法:

 var hID = from APPLICANT in context.APPLICANTs
                          join CONTACT_INFO in context.CONTACT_INFO on APPLICANT.HOH_UPI equals CONTACT_INFO.HOH_UPI
                          where (APPLICANT.HOH_UPI.ToString().StartsWith(model.HOHUPI)) && (APPLICANT.RESP_FRST.StartsWith(model.FirstName))
                          && (APPLICANT.RESP_LST.StartsWith(model.LastName)) && (CONTACT_INFO.HM_PHN_NMB.ToString().StartsWith(model.HM_PHN_NMB))
                          orderby APPLICANT.RESP_FRST
                          select APPLICANT;

               model.SearchResults = hID.ToPagedList(pageIndex, RecordsPerPage);

这有效,但前提是用户在所有 4 个文本框(名字、姓氏、hohupi 和电话号码)中输入值。我需要帮助制定查询,以便用户只能搜索 1 或任何组合文本框。

申请表的主键是HOH_UPI,Contact_Info表的外键是HOH_UPI。

非常感谢您的帮助!

【问题讨论】:

    标签: c# entity-framework linq linq-to-sql lambda


    【解决方案1】:

    我搞定了:

     var hID = from APPLICANT in context.APPLICANTs
                              join CONTACT_INFO in context.CONTACT_INFO on APPLICANT.HOH_UPI equals CONTACT_INFO.HOH_UPI
                              where (APPLICANT.HOH_UPI.ToString().StartsWith(model.HOHUPI) || model.HOHUPI == null) && (APPLICANT.RESP_FRST.StartsWith(model.FirstName) || model.FirstName == null)
                              && (APPLICANT.RESP_LST.StartsWith(model.LastName) || model.LastName == null) && (CONTACT_INFO.HM_PHN_NMB.ToString().StartsWith(model.HM_PHN_NMB) || model.HM_PHN_NMB == null)
                              orderby APPLICANT.RESP_FRST
                              select APPLICANT;
    

    知道在哪里使用逻辑 AND (&&) 和 OR (||) 是关键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多