Can anyone reduce these 3 LINQ to SQL statements into one? - c#

Ok so I am trying to get all the Companies assigned to BOTH courses that exist in a course mapping table.
The course mapping table has 2 FK CourseIDs, that point to two different courses in the same table.
Each course has a bundle, and the companies are assigned to bundles.
I am trying to select all the companies that are assigned to both bundles from both courses.
I have been able to do this (Edit: apparently not, because of the OR, can anyone fix this too?) using 3 different LINQ queries, but I am hoping there is a way to reduce it into one for both brevity and performance:
Bundle vegasBundle = (from cm in db.VegasToPegasusCourseMaps
join c in db.Courses on cm.VegasCourseID equals c.CourseID
join b in db.Bundles on c.BundleID equals b.BundleID
where cm.VPCMapID == CourseMapID
select b).FirstOrDefault();
Bundle pegasusBundle = (from cm in db.VegasToPegasusCourseMaps
join c in db.Courses on cm.PegasusCourseID equals c.CourseID
join b in db.Bundles on c.BundleID equals b.BundleID
where cm.VPCMapID == CourseMapID
select b).FirstOrDefault();
IQueryable<Company> companyAssigned = from cb in db.CompanyBundles
join c in db.Companies on cb.CompanyID equals c.CompanyID
where cb.BundleID == vegasBundle.BundleID || cb.BundleID == pegasusBundle.BundleID
select c;
return companyAssigned.ToList();

Here's your simplified query:
return (
from cm in db.VegasToPegasusCourseMaps
join cv in db.Courses on cm.VegasCourseID equals cv.CourseID
join bv in db.Bundles on cv.BundleID equals bv.BundleID // vegasBundle
join cp in db.Courses on cm.PegasusCourseID equals cp.CourseID
join bp in db.Bundles on cp.BundleID equals bp.BundleID // pegasusBundle
from cb in db.CompanyBundles // OR-Join must be in the where clause
join c in db.Companies on cb.CompanyID equals c.CompanyID
where cm.VPCMapID == CourseMapID
&& (cb.BundleID == bv.BundleID || cb.BundleID == bp.BundleID)
select c
).ToList();
[Update]:
Here's the query that matches your requirements. It will only match companies that match both courses.
return (
from cm in db.VegasToPegasusCourseMaps
join cv in db.Courses on cm.VegasCourseID equals cv.CourseID
join bv in db.Bundles on cv.BundleID equals bv.BundleID // vegasBundle
join cbv in db.CompanyBundles on bv.BundleId equals cbv.BundleId
join cv in db.Companies on cbv.CompanyID equals cv.CompanyID
join cp in db.Courses on cm.PegasusCourseID equals cp.CourseID
join bp in db.Bundles on cp.BundleID equals bp.BundleID // pegasusBundle
join cbp in db.CompanyBundles on bp.BundleId equals cbp.BundleId
join cp in db.Companies on cbp.CompanyID equals cp.CompanyID
where cm.VPCMapID == CourseMapID
&& cv.CompanyID == cp.CompanyID
select cv
).ToList();
Another thing: since you have the following relationship: Courses.BundleId => Bundles.BundleId => CompanyBundles.BundleId, you can actually join Courses to CompanyBundles and skip the Bundles join. But SQL probably does this anyway.

Here's a modification for your last query to ensure that you get companies that are enrolled in both bundles:
IQueryable<Company> companyAssigned =
from c in db.Companies
join vcb in db.CompanyBundles on c.CompanyID equals vcb.CompanyID
join pcb in db.CompanyBundles on c.CompanyID equals pcb.CompanyID
where vcb.BundleID == vegasBundle.BundleID && pcb.BundleID == pegasusBundle.BundleID
select c;
For combining the queries, you can look at Scott Rippey's answer.

Related

LINQ Left Join 3 tables with OR operator

I have this SQL query:
SELECT * FROM [CMS_MVC_PREPROD].[dbo].[T_MEMBER] m
left outer join [CMS_MVC_PREPROD].[dbo].[T_COMPANY] c
ON m.Company_Id = c.Id
left outer join [CMS_MVC_PREPROD].[dbo].[T_ADRESSE] a
ON m.Id = a.Member_Id OR a.Company_Id = c.Id
But i could not translate it to Linq
I have some trouble with this line in particular:
ON m.Id = a.Member_Id OR a.Company_Id = c.Id
EDIT: I try this query from Ehsan Sajjad
from m in db.Member
join c in db.T_Company on m.Company_Id equals c.Id into a
from c in a.DefaultIfEmpty()
from ta in db.T_Address
where m.Id == ta.Member_Id || ta.Company_Id == c.Id
But it only returns members who have an address and i want all members. Maybe it will work with a full join
Thanks in advance
LINQ only supports equi-joins directly. You'll have to use a different query pattern:
from m in db.MEMBER
//add join to "c" here
from a in (
from a db.ADRESSE
where m.Id == a.Member_Id || a.Company_Id == c.Id
select a).DefaultIfEmpty()
select new { m, a }
Just a sketch. The trick is using DefaultIfEmpty on a subquery. Both L2S and EF can translate this to an OUTER APPLY which is equivalent to a LEFT JOIN.
You can write this way to make it work:
from m in db.Member
join c in db.T_Company on m.Company_Id equals c.Id into a
from c in a.DefaultIfEmpty()
from ta in db.T_Address
where m.Id == ta.Member_Id || ta.Company_Id == c.Id

Return navigation property within join query

In building a patient appointment application I need to return patients with its navigation property patientDetails while those returned match a sessionId that is not directly deduced from the patient but rather from a series of other navigation properties. This in itself is not difficult, like plain SQL joins can be used, it's just that my navigation property patientDetails is never included.
The include path is correct, in case anyone asks.
using (DbEntities db = new DbEntities())
{
List<tblPatient> res = (from s in db.tblSessions
join b in db.tblBookings on s.id equals b.sessionId
join r in db.tblReferrals on b.referralId equals r.id
join a in db.tblAttendanceStatus on b.attendanceStatus equals a.id
join p in db.tblPatients.Include("tblPatientDetail") on r.patientId equals p.id
join pd in db.tblPatientDetails on p.patientDetailsId equals pd.id
where s.id == id
select p).ToList();
return res;
}
It appears to make no difference whether or not I include the .include.
What have I overlooked?
Includes are ignored when you use join or group by. You can change your query to use where instead
List<tblPatient> res = (from p in db.tblPatients.Include("tblPatientDetail")
where
(from s in db.tblSessions
join b in db.tblBookings on s.id equals b.sessionId
join r in db.tblReferrals on b.referralId equals r.id
join a in db.tblAttendanceStatus on b.attendanceStatus equals a.id
where r.patientId == p.id
where s.id == id
select 1).Any()
select p).ToList()

LINQ Join not returning results if second or third table empty

I've three tables :
Module_Articles_Articles
Module_Articles_Categories
Module_Articles_Comments
and I want to display my articles in repeater my query :
var articles =
(from a in context.Module_Articles_Articles
join c in context.Module_Articles_Categories on a.CategoryID equals c.CategoryID
join co in context.Module_Articles_Comments on a.ArticleID equals co.ArticleID
where a.IsDraft == false
orderby a.ArticleID descending
select new
{
a.ArticleID,
a.ArticleTitle,
a.ArticleContent,
a.Image,
a.Sender,
a.SentDate,
a.Summary,
a.Likes,
a.Dislikes,
a.Tags,
a.PostMode,
c.CategoryID,
c.CategoryTitle,
AcceptedCommentsCount =
(from com in context.Module_Articles_Comments where com.ArticleID == a.ArticleID && com.Status select com)
.Count(),
DeniedCommentsCount =
(from com in context.Module_Articles_Comments where com.ArticleID == a.ArticleID
&& com.Status == false select com)
.Count()
}).ToList();
but when Module_Articles_Categories or Module_Articles_Comments are empty my query returns nothing!
Is my code true? If not, how can I do this?
you want an OUTTER JOIN, which can be accomplished in a query like this by simply adding .DefaultIfEmpty()
from a in context.Module_Articles_Articles
join c in context.Module_Articles_Categories on a.CategoryID equals c.CategoryID into ca
from c in cs.DefaultIfEmpty()
join co in context.Module_Articles_Comments on a.ArticleID equals co.ArticleID into com
from co in com.DefaultIfEmpty()
where a.IsDraft == false
orderby a.ArticleID descending
select new ...
You are not getting results because your LINQ joins result in INNER JOINs. You probably want LEFT JOINs. Do it as follows.
var articles =
(from a in context.Module_Articles_Articles
join c in context.Module_Articles_Categories on a.CategoryID equals c.CategoryID into joinTable1
from c in joinTable1.DefaultIfEmpty()
join co in context.Module_Articles_Comments on a.ArticleID equals co.ArticleID into joinTable2
from co in joinTable2.DefaultIfEmpty()
where a.IsDraft == false
orderby a.ArticleID descending
select new
{
a.ArticleID,
a.ArticleTitle,
a.ArticleContent,
a.Image,
a.Sender,
a.SentDate,
a.Summary,
a.Likes,
a.Dislikes,
a.Tags,
a.PostMode,
c.CategoryID,
c.CategoryTitle,
AcceptedCommentsCount =
(from com in context.Module_Articles_Comments where com.ArticleID == a.ArticleID && com.Status select com)
.Count(),
DeniedCommentsCount =
(from com in context.Module_Articles_Comments where com.ArticleID == a.ArticleID
&& com.Status == false select com)
.Count()
}).ToList();

How can I with LiNQ select items from a list based on another list?

I am creating a game, and my table layout looks like this:
dbPlayer:
Id (int)
...
dbGame:
Id (int)
Finished (bool)
...
dbGamePlayer:
GameId
PlayerId
...
Given a Players ID, how can I select all games that the player is involved in, but has not (true) finished?
This is what I've go so far:
from g in dbGame
join gp in dbGamePlayer on gp.GameId equals g.Id
join p in dbPlayer on p.Id equals gp.PlayerId
where p.Id == 1 && g.Finished == false
select g
But I'm getting errors all over the place. Sorry, I'm new at LINQ
Your LINQ Statement is wrong.
The joint object (gp) has to be on the right side of the equals-Statement.
join gp in dbGamePlayer on g.Id equals gp.GameId
Same applies to the second join:
join p in dbPlayer on gp.PlayerId equals p.Id
So the full statement should look like:
IEnumerable query = (from g in dbGame
join gp in dbGamePlayer on g.Id equals gp.GameId
join p in dbPlayer on gp.PlayerId equals p.Id
where p.Id == 1 && g.Finished == false
select g);
But the error
Name model is not in scope on the left side of equals.
Consider swapping the expression on the either side of equals.
should have told you that.

How do I build up a LINQ => SQL / entities query (with joins) step-by-step?

I have the following two LINQ queries:
public int getJobsCount()
{
var numJobs =
(from j in dbConnection.jobs
join i in dbConnection.industries on j.industryId equals i.id
join c in dbConnection.cities on j.cityId equals c.id
join s in dbConnection.states on j.stateId equals s.id
join pt in dbConnection.positionTypes on j.positionTypeId equals pt.id
select j).Count();
return numJobs;
}
public List<Job> getJobs()
{
var jobs =
(
from j in dbConnection.jobs
join i in dbConnection.industries on j.industryId equals i.id
join c in dbConnection.cities on j.cityId equals c.id
join s in dbConnection.states on j.stateId equals s.id
join pt in dbConnection.positionTypes on j.positionTypeId equals pt.id
orderby j.issueDatetime descending
select new Job { x = j.field, y = c.field, etc }
).Skip(startJob - 1).Take(numJobs);
return jobs;
}
There's a lot of duplicate code in there - the "from", and "join" lines are identical, and I'll be adding in some "where" lines as well that will also be identical.
I tried adding a method that returned an IQueryable for the first part:
public IQueryable getJobsQuery()
{
var q =
from j in dbConnection.jobs
join i in dbConnection.industries on j.industryId equals i.id
join c in dbConnection.cities on j.cityId equals c.id
join s in dbConnection.states on j.stateId equals s.id
join pt in dbConnection.positionTypes on j.positionTypeId equals pt.id;
return q;
}
...but I get "a query body must end with a select clause or a group clause".
If I add a select clause on to the end off that function, I can't call count() on the result:
// getJobsQuery:
var q = from j in dbConnection.jobs
join i in dbConnection.industries on j.industryId equals i.id
join c in dbConnection.cities on j.cityId equals c.id
join s in dbConnection.states on j.stateId equals s.id
join pt in dbConnection.positionTypes on j.positionTypeId equals pt.id
select new { a = j.y, b = c.z }
// another method:
var q = getJobsQuery();
var numJobs = q.Count(); // "IQueryable doesn't contain a definition for count"
Is there a way to build up this query step-by-step to avoid duplicating a whole lot of code?
There are two ways of writing LINQ-queries, and though it doesn't really matter witch one you use it's good to know both of them cause they might learn you something about how LINQ works.
For instance, you have a set of jobs. If you were to select all jobs with an industryId of 5 (wild guess of data-types) you'd probably write something like this:
from j in dbConnection.jobs
where j.inustryId == 5
select j;
The very same query can also be written like this
dbConnections.jobs.Where(j => j.industryId == 5);
Now, I'm not here to preach saying one way is better than the other, but here you can clearly see how LINQ using the extension-methods syntax automatically selects on the iterated object (unless you do a select), whereas in the query-syntax you must do this explicitly. Also, if you were to add inn another where clause here it would look something like this:
from j in dbConnection.jobs
where j.inustryId == 5 // not using && here just to prove a point
where j.cityId == 3 // I THINK this is valid syntax, I don't really use the query-syntax in linq
select j;
While in the extension-methods you can just append more method-calls like so:
dbConnections.jobs.Where(j => j.industryId == 5)
.Where(j => j.cityId == 3);
Now this is good to know cause this means you can just put your linq-query inside a function an continue querying it. And all you need to do to make it work in your case is just explicitly select the starting variable j, or all the variables you need like so:
var q =
from j in dbConnection.jobs
join i in dbConnection.industries on j.industryId equals i.id
join c in dbConnection.cities on j.cityId equals c.id
join s in dbConnection.states on j.stateId equals s.id
join pt in dbConnection.positionTypes on j.positionTypeId equals pt.id;
select new {j = j, i = i, c = c, s = s, pt = pt };
return q;
Then you should be able to do for instance this:
getJobsQuery().Where(a => a.i.id == 5); // I used a as a name for "all", like the collection of variables
or using the query-syntax
from a in getJobsQuery()
where a.i.id == 5
select a;
Would this be better solved by returning a set of data (e.g. the common data) and querying for a subset of that data?
E.g. [pseudocode]
var allJobs =
(from j in dbConnection.jobs
join i in dbConnection.industries on j.industryId equals i.id
join c in dbConnection.cities on j.cityId equals c.id
join s in dbConnection.states on j.stateId equals s.id
join pt in dbConnection.positionTypes on j.positionTypeId equals pt.id
select j);
var myJobs = allJobs.OrderBy(j => j.issuedate).skip(expr).Take(allJobs.Count);
or similar...

Categories

Resources