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
Related
Please note below is entirely made up for example sake. I have a similar query based on an sql code but couldn't translate it to LINQ to get correct value.
The sql basically looks like this:
select * from customers c
join proucts p on c.id = p.customerid
join credit r on r.customerid=c.id and ISNULL(r.trandate, c.registeredDate) >= c.registeredDate
I also tried to tweak the above sql and put the condition inside where and it also returns the same value I am getting in my #2 LINQ below(which is incorrect).
How can I use c (customer) inside .Where of credit? see code
1.
from c in customers
join p in products on c.id = p.customerid
join cr in credit.Where(r=> r.tranDate => c.registeredDate!=null?c.registeredDate : r.purchaseDate) on c.id=cr.customerid
...
2.
I know you would suggest why not just put it in a where below like below but I am getting incorrect value.
from c in customers
join p in products on c.id = p.customerid
join cr in credit on c.id=cr.customerid
where r.tranDate => c.registeredDate!=null?c.registeredDate : r.purchaseDate
Is there a workaround? I have tried tons of others but won't get me the correct one.
LINQ supports only equijoins. Any additional criteria should go to where clause. And yes, the other range variables are inaccessible from the join inner sequence, so the filtering should happen before or after the join.
So this SQL query:
select * from customers c
join products p on c.id = p.customerid
join credit r on r.customerid = c.id
and ISNULL(r.trandate, c.registeredDate) >= c.registeredDate
directly translates to this LINQ query:
from c in customers
join p in products on c.id equals p.customerid
join cr in credit on c.id equals cr.customerid
where (cr.tranDate ?? c.registeredDate) >= c.registeredDate
select new { c, p, cr };
Optionally, the condition
(cr.tranDate ?? c.registeredDate) >= c.registeredDate
can be replaced with
(cr.tranDate == null || cr.tranDate >= c.registeredDate)
I want to check values that are present in other table, not from fixed list or array. here is an example of what I need. Actually I am querying EF.
Database_EF db = new Database_EF();
var listA = (from a in db.a
where a.id in
(from b in db.b
join c in db.c on b.id equals c.id
where c.col1 equals 'something'
select b.id)
select a.id).ToList();
I am new to linq. Thanks.
Should be something like this:
var listA = (from a in db.a
where (from b in db.b
join c in db.c on b.id equals c.id
where c.col1 == "something"
select b.id).Contains(a.id)
select a.id).ToList();
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()
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.
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...