简体   繁体   English

使用 LINQ 或 EF 执行查询以从多个表中获取记录

[英]Execute query using LINQ or EF to fetch records from multiple tables

I've been searching for a while now.我已经搜索了一段时间了。 But all the solutions seems to be different than what I expect.但是所有的解决方案似乎都与我的预期不同。

So this is my query in SQL:-所以这是我在 SQL 中的查询:-

Select * from
(
    select Name,Description Descr from CourseTbl
    union all
    select MainDesc Name,MainDesc Descr from CoursedescTbl
    union all
    select SubHeading Name,SubDesc Descr from CourseSubDesc
    union all
    select Name,Descr as Descr from InternTbl
)A where A.Name like '%D%' or A.Descr like '%D%'

I want to execute the above query using LINQ or EF.我想使用 LINQ 或 EF 执行上述查询。 and return the list in Json format.并以 Json 格式返回列表。 So I tried many failed attempts and this is one of them:-所以我尝试了很多失败的尝试,这是其中之一:-

public JsonResult SearchDetail()
    {
        string SearchKey = Request.Form["SearchName"].ToString();

        IEnumerable<SearchList> QueryResult;

        using (EBContext db = new EBContext())
        {
            try
            {
                QueryResult = 
                    (from x in db.Courses 
                     select new { A = x.Name, B = x.Description })
                    .Concat(from y in db.CourseDesc 
                            select new { A = y.MainHeading, B = y.MainDesc })
                    .Concat(from z in db.CourseSubDesc 
                            select new { A = z.SubDesc, B = z.SubHeading })
                    .Concat(from w in db.Interns 
                            select new { A = w.Name, B = w.Descr })
                    .ToList();                    
            }
            catch (Exception ex)
            {
                return new JsonResult 
                {
                    Data = ex.Message, 
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet 
                };
            }



            return new JsonResult 
            { 
                Data = QueryResult, 
                JsonRequestBehavior = JsonRequestBehavior.AllowGet 
            };
        }

    }

And my SearchList Class is like this:-我的 SearchList 类是这样的:-

public class SearchList
{
    public string Name { get; set; }
    public string Descr { get; set; }
}
  1. I'm not able to put the where clause in linq query which will search in all table.我无法将 where 子句放在将在所有表中搜索的 linq 查询中。
  2. I'm getting error when I assign queryresult to my ef query.当我将 queryresult 分配给我的 ef 查询时出现错误。 It says cannot cast to Innumerable.它说不能投射到无数。

Thanks in Advance.提前致谢。

Could you explain more on the error you are getting?你能解释一下你得到的错误吗?

Also, have you tried using .Union() in linq?另外,您是否尝试过在 linq 中使用.Union()

QueryResult = db.Courses.Select(x=> new { A = x.Name, B= x.Description})
             .Union(db.CourseDesc.Select(y=> new {A = y.MainHeading, B = y.MainDesc })
             .Union( //so on 
             .ToList(); //this isn't necessary 

Edit: There are two ways to input where clause, either with each search, or at the end:编辑:有两种方法可以输入 where 子句,要么在每次搜索时,要么在最后:

 QueryResult = db.Courses.Where(x=>x.Name == "Name").Select(x=> new { A = x.Name, B= x.Description})
             .Union(db.CourseDesc.Where(y=>y.MainHeading == "Name").Select(y=> new {A = y.MainHeading, B = y.MainDesc })
             .Union( //so on 
             .ToList(); 

Or:或者:

  QueryResult = db.Courses.Where(x=>x.Name == "Name").Select(x=> new { A = x.Name, B= x.Description})
             .Union(db.CourseDesc.Where(y=>y.MainHeading == "Name").Select(y=> new {A = y.MainHeading, B = y.MainDesc })
             .Union( //so on 
             //Where can go either before or after .ToList
             .Where(item=>item.A == "Name")
             .ToList();

You did not say what error/exception you are getting.你没有说你得到了什么错误/异常。 But your QueryResult is of type IEnumerable<SearchList> and you appear to be assigning it an enumerable of anonymous type { A, B } .但是您的QueryResultIEnumerable<SearchList>类型,您似乎正在为其分配匿名类型{ A, B }的枚举。

Try this:尝试这个:

QueryResult = (from x in db.Courses 
                 select new SearchList { Name = x.Name, Descr = x.Description })
                 .Concat(...)
                 .ToList();

Or或者

QueryResult = db.Courses.Select(x => new SearchList 
                 { Name = x.Name, Descr = x.Description})
                .Concat(...)
                .ToList();

UPDATE更新

Your #2 issue will be fixed if you changed your select to new up a SearchList as I did above, instead of new -ing an anonymous type.如果您像我上面所做的那样将选择更改为new一个SearchList ,而不是new一个匿名类型,那么您的 #2 问题将得到解决。

As for your issue #1, you should insert the Where() before your Select() :至于您的问题#1,您应该在Select()之前插入Where() Select()

result1 = db.Courses
                .Where(x => x.Name.Contains('D') || x.Description.Contains('D'))
                .Select(x => new SearchList { Name = x.Name, Descr = x.Description});
result2 = db.CourseDesc
                .Where(y => y.MainHeading.Contains('D') || y.MainDesc.Contains('D'))
                .Select(y => new SearchList { Name = y.MainHeading, Descr = y.MainDesc});
result3 = db.CourseSubDesc
                .Where(...)
                .Select(...);

QueryResult = result1.Concat(result2).Concat(result3).ToList();

Doing Where() as part of the query on each table is important so you do not fetch all records from that table, unlike if you do the Where() after Concat() .在每个表上执行Where()作为查询的一部分很重要,因此您不会从该表中获取所有记录,这与在Concat()之后执行Where()不同。 Also note that Concat() may throw an ArgumentNullException .另请注意, Concat()可能会抛出ArgumentNullException

Take the lists Separately and query and concat check this example分别取列表并查询和连接检查此示例

        List<string> a = new List<string>() { "a", "b", "c" };
        List<string> b = new List<string>() { "ab", "bb", "cb" };

        IEnumerable<SearchList> QueryResult = 
            a.Where(x => x.Contains("a")).Select(x => new SearchList() { Name = x, Descr = x })
            .Concat(b.Where(x => x.Contains("a")).Select(x => new SearchList() { Name = x, Descr = x }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM