Linq查询如何在不使用联接的情况下从多个表中获取数据

时间:2019-06-13 09:48:11

标签: c# sql-server asp.net-mvc

我的数据库中有3个彼此无关的表。我想要的是在我的网站上实施搜索操作。这样,当在搜索框中提交单词时,查询将遍历所有表,并在找到该单词的任何地方获取数据。我可以从单个表中获取数据。

    public ActionResult Searchresult(string searchString)
    {
        var article = (from c in db.Tbl_Article select c );
        article = article.Where(s => s.Article_Title.Contains(searchString));

        var blog = (from c in db.Tbl_Blog select c );
        blog = blog.Where(s => s.Blog_Title.Contains(searchString));

        var history = (from c in db.Tbl_History select c);
        history = history.Where(s => s.Title.Contains(searchString));

        var result = article.Select(x => x.Article_Title).Union(blog.Select(x => x.Blog_Title)).Union(history.Select(x => x.Title)).ToList();

    //  ViewBag.result = result.ToString();

        return View(result);
    }

请不要混淆我在行动方法中返回的内容,它是该问题的很长且不必要的代码。

通过使用此代码,我成功地从一张表中获得了搜索结果。 现在,我希望从数据库中存在的所有表中获得相同的结果。那就是我被困住的地方。我搜索了很多文章,但是没有找到我自己问的最后一个解决方案。

谢谢

2 个答案:

答案 0 :(得分:1)

这可能有效

   Public ActionResult Index(string searchString)
    {
     var query1 = (from c in db.TableArticle select c);
       if (!String.IsNullOrEmpty(searchString))
         {
    query1 = query1.Where(s => 
            s.Article_Title.Contains(searchString)
    || s.Article_Description.Contains(searchString) || 
             s.Written_By.Contains(searchString) || 
             s.Organisation.Contains(searchString)
   ||s.Source.Contains(searchString));
            }
    var query2 = (.......);
    var query3 = (.......);

    var finalResult = query1.Select(x => x.columnName).Union(query2.Select(x => x.columnName)).Union(query3.Select(x => x.columnName));
    // OR
    var finalResult = query1.Select(x => x.columnName).Concat(query2.Select(x => x.columnName)).Concat(query3.Select(x => x.columnName));
    }

答案 1 :(得分:0)

我刚刚实现并签入了本地相同的查询,并且运行正常, 给出的答案是正确的@Khairul Alam,

我刚刚优化了代码,并在本地运行相同的代码

var searchString = "School";
        if (!String.IsNullOrEmpty(searchString))
        {
            var query1 = _context.Jobs.Where(s =>
                     s.JobTitle.Contains(searchString)
             || s.LocationDescription.Contains(searchString));

            var query2 = _context.Recruiters.Where(s =>
                    s.RecruiterName.Contains(searchString));

            var query3 = _context.Sectors.Where(s =>
                    s.SectorName.Contains(searchString));
            try
            {
                var finalResult = query1.Select(x => x.JobTitle).Union(query2.Select(x => x.RecruiterName)).Union(query3.Select(x => x.SectorName)).ToList();
            }
            catch (Exception)
            {
                throw;
            }

包含输出最终结果的图像

Click here for Final output

如果您仍然遇到问题,请共享一些代码,或者在哪里准确找到错误,以便我们解决问题

希望这对您有帮助

谢谢