简体   繁体   中英

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:-

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. and return the list in Json format. 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:-

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.
  2. I'm getting error when I assign queryresult to my ef query. 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?

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:

 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 } .

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.

As for your issue #1, you should insert the Where() before your 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() . Also note that Concat() may throw an 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 }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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