SQL Server .NET SQL Query joining two different tables

kkih6yb8  于 12个月前  发布在  .NET
关注(0)|答案(1)|浏览(118)

I'm brand new to .net MVC, and while I have some basic experience with writing SQL queries, I'm not sure how to go about what I need to do for .NET.

My initial query looks like this:

var results = (from s in db.Members 
               join sa in db.FocusArea on s.ID equals sa.MemberID 
               where sa.Area == SearchString 
               select new { s.ID, s.Name, s.Overview }).ToList();

This is not functioning correctly. It is seaching in the s.Overview for some reason. And, I need to make this query much more complicated. In short, I have three tables I need to search across. And with this query, it is not working:

var conceptResults = (from s in db.Cohorts 
                      join oa in db.OutcomeArea on s.ID equals oa.CohortID 
                      where ((oa.Area.Contains(SearchString)) 
                         || (oa.OutcomeType.Contains(SearchString))) 
                      select new { s.ID, s.Name, s.Overview }).ToList();
  1. I need to use my SearchString to search for matches in both Area and Description in db.FocusArea.
  2. I also need to use my SearchString to search for matches (contains) in another table db.SpecificFocusAreas for column SFocusArea where again the join is the ID/MemberID.

Is there a way to essentially do a join or join type of statement? I don't want to join all three tables because I am looking for results from either of the two joins, not from all joins.

oknwwptz

oknwwptz1#

For your specified conditions, you can join three tables as done below where third table is joined by id as needed :

var conceptResults = (
        from s in db.Cohorts
        join oa in db.OutcomeArea on s.ID equals oa.CohortID into outcomeAreas
        from oa in outcomeAreas.DefaultIfEmpty()
        
        join fa in db.FocusArea on s.ID equals fa.CohortID into focusAreas
        from fa in focusAreas.DefaultIfEmpty()
        
        join sfa in db.SpecificFocusAreas on s.ID equals sfa.MemberID into specificFocusAreas
        from sfa in specificFocusAreas.DefaultIfEmpty()
        
        where (oa != null && (oa.Area.Contains(SearchString) || oa.OutcomeType.Contains(SearchString)))
              || (fa != null && fa.Area.Contains(SearchString))
              || (sfa != null && sfa.SFocusArea.Contains(SearchString))
        
        select new { s.ID, s.Name, s.Overview }
    ).ToList();

相关问题