How to execute query to select multiple attributes subject to several where clauses across two tables

StackOverflow https://stackoverflow.com/questions/22151518

  •  19-10-2022
  •  | 
  •  

Question

I have two tables from which I want to select data from:

Document_Data
Document_info

I want to execute the following query :

SELECT DISTINCT Document_Data.DOC_CLASS, TITLE FROM Document_info,Document_Data WHERE (((DOC_STATUS = '1') AND (PORTAL = 'First Page'))) AND (Document_info.DOC_NUMBER = Document_Data.DOC_NUMBER AND Document_info.REVISION = Document_Data.REVISION AND STATUS = 'CURRENT' AND Document_Data.DOC_CLASS = 'MESSAGE')

Can anyone give me info on how to execute the following query using Linq?

Was it helpful?

Solution

I have made a few assumptions since your query did leave off a few table names. I assumed that STATUS was on the Document_data table and DOC_STATUS was on the Document_info table. If its any different, it shouldn't be hard to modify this query to work.

DbContext is your entity framework context or wherever your store your db collections.

dbContext.Document_info.Where(i => i.DOC_STATUS == "1" && i.PORTAL == "First Page")
    .Join(dbContext.Document_data.Where(d => d.DOC_CLASS == "MESSAGE" && d.STATUS == "CURRENT"),
        i => new { i.REVISION, i.DOC_NUMBER }, //Document_info
        d => new { d.REVISION, d.DOC_NUMBER }, //Document_data
        (i, d) => new { d.DOC_CLASS, i.TITLE }) //(Document_info, Document_data)
    .Distinct()
    .ToList();

The way this works is that it first filters the document_info table to what you wanted from there. It then joins it with a filtered Document_data table on a composite "key" made up of REVISION and DOC_NUMBER. After that, it runs the Distinct and executes the whole query with a ToList.

The above should compile to valid SQL (at least it would using the MySQL connector...I haven't tried anything like that with MSSQL, but I assume that since the MSSQL one works better than MySQL so it would make sense that it would work there too). This particular query would come out to be a little convoluted, however, and might not work very optimally unless you have some foreign keys defined on REVISION and DOC_NUMBER.

I would note that your query will only return things where d.DOC_CLASS == "MESSAGE" and so your results will be quite repetitious.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top