Question

I have the following queries:

var majorClients = maj in dbContext.MajorClients
                   where (maj.startdate > startDate)
                   where (maj.status == "Active")
                   Select new Client{EntityPK = maj.mjPrimaryKey,Name = maj.name, Type = "Maj"};

var minorClients = min in dbContext.MinorClients
                   where (min.startdate > startDate)
                   where (min.status == "Active" || min.status== "Inactive")
                   Select new Client{EntityPK = min.mnPrimaryKey,Name = min.name, Type = "Min"};

There are clients that could appear in both major and minor tables. I would like to return a list of all occurrences of clients in both tables, however if there are matching clients by name, then I would only want to return the matching record from the majorClients table.

I have written a sql query to return the results:

SELECT mjPrimaryKey AS EntityPK,name,'Maj' AS TYPE 
FROM majorClients 
WHERE status = 'Active' AND startDate > @startDate
UNION ALL
SELECT mnPrimaryKey,name,'Min' FROM minorClients
WHERE status IN ('Active','Inactive') AND startDate > @startDate
WHERE name NOT IN (SELECT name FROM majorClients WHERE status = 'Active' AND startDate > @startDate)

How would I represent this query in linq?

Was it helpful?

Solution

Try this linq. To exclude duplicates from minorClients, I've used Contains method. To union all objects - Union method:

var majorClients = from maj in dbContext.MajorClients
                   where maj.startdate > startDate
                        && maj.status == "Active"
                   select new Client
                    {
                        EntityPK = maj.mjPrimaryKey,
                        Name = maj.name, 
                        Type = "Maj"
                    };

var minorClients = from min in dbContext.MinorClients
                   where min.startdate > startDate
                        && min.status == "Active" || min.status== "Inactive"
                        && !(from maj in dbContext.MajorClients
                             where maj.startdate > startDate
                                && maj.status == "Active"
                             select maj.name).Contains(min.Name)
                   select new Client
                        {
                            EntityPK = min.mnPrimaryKey,
                            Name = min.name, 
                            Type = "Min"
                        };

var allClients = majorClients.Union(minorClients);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top