How do you Left join 'Is Not Null' using linq? - c#

I am having some issues getting my LINQ statement to work. I am left joining a table, secondTable, where one of the columns can be null but I only need the records where this column is not null. I'm not sure how to get the following into a LINQ expression
LEFT JOIN secondTable b ON a.ID = b.oneTableID AND b.name IS NOT NULL
So far my LINQ is:
var list = await (from one in dbRepository.oneTable
join two in dbRepository.secondTable
on new { name = one.name, phone = one.phone, height = { is not null} } equals new
{ name = two.name, phone = two.phone, height = two.height
into temp
from two in temp.DefaultIfEmpty()
select new.....
Any Ideas?
EDIT 1: I was able to find a solution.
var list = await (from one in dbRepository.oneTable
join two in dbRepository.secondTable
on new { name = one.name, phone = one.phone, height = false } equals new
{ name = two.name, phone = two.phone, height = string.IsNullOrEmpty(two.height)}
into temp
from two in temp.DefaultIfEmpty()
select new.....

You have to use SelectMany possibility to create LEFT JOIN:
var query =
from one in dbRepository.oneTable
from two in dbRepository.secondTable
.Where(two => two.name = one.name && two.phone == one.phone
&& two.height != null)
.DefaultIfEmpty()
select new.....

Try this one:
var list = await (from one in dbRepository.oneTable
join two in dbRepository.secondTable
on new { name = one.name, phone = one.phone}
equals new
{ name = two.name, phone = two.phone}
into temp
from two in temp.DefaultIfEmpty()
where one.height == null || one.height = two.height
select new.....

Related

C# Linq - Issue with joining3 tables - Error CS1941

I'm trying to fetch the records based on this query
documentList = await (from doc in _dbContext.Documents
join doce in _dbContext.StudentEnrollments on doc.ID equals doce.ID
join enr in _dbContext.Enrollments on doce.EnrollmentID equals enr.Id
where enr.name != null
&& (enr.faiedlattemps = 1 || enr.ReferenceNumber != null)
select doc);
I am getting the
"Correlates the elements of two sequences based on matching key error. The default equality comparer is used to compare keys"
I tried with this as well
var result = from x in _dbContext.Documents
join y in _dbContext.StudentEnrollments
on new { X1 = x.ID } equals new { X1 = y.ID}
join z in _dbContext.Enrollments on new { Z1 = y.EnrollmentID } equals new { Z1 = z.Id}
select new
{
/// Columns
};
Getting the same error

How to get the count of values in table using linq

im required to make a query to db to fetch data fro a highchart widget in our site here is the code I use currently,
var highChartsData =
(from a in db.roomdetails
join b in db.ApplySchedule on a.RoomId equals b.RoomID
where b.Status == true
select new HighlinePie
{
Title = a.RoomName,
Date = b.MDate,
Value = db.ApplySchedule.Where(x => x.RoomID == a.RoomId).GroupBy(x=>x.MDate).Count(),
}).ToList();
The problem with this approach is right now get the total count but what i need is the count based on date, for example if there was two entry on date 12/09/20201 and three entry on 14/09/20201 the data should be "Title,12/09/20201,2","Title,14/09/20201,3".
You have to use grouping:
var groupQuery =
from a in db.roomdetails
join b in db.ApplySchedule on a.RoomId equals b.RoomID
where b.Status == true
group b by new { a.RoomName, b.MDate } into g
select new HighlinePie
{
Title = g.Key.RoomName,
Date = g.Key.MDate,
Value = g.Count()
};
var highChartsData = groupQuery.ToList();

Converting complex SQL with FULL JOIN to Linq

I am trying to convert a SQL statement to Linq/Entity Framework, and am having a difficult time. Below is the SQL.
SELECT
trust.FName,
trust.MName,
trust.LName
tla.Address,
tma.Address,
at.Descr
FROM CLIENTSSUITS cs
INNER JOIN TRUSTS trust ON trust.SSN = cs.CLIENT
FULL JOIN ADV_TYPES at ON at.CODE = trust.AT
LEFT OUTER JOIN CLIENTADDRESSES tla ON tla.SSN = trust.SSN AND tla.ID = 'L'
LEFT OUTER JOIN CLIENTADDRESSES tma ON tma.SSN = trust.SSN AND tma.ID = 'M'
WHERE cs.PRIMARY = w AND SecondaryRole = x AND cs.ID = y AND cs.Rev = z AND cs.DELETED = 0
GROUP BY trust.FName,
trust.MName,
trust.LName,
tla.Address,
tma.Address,
at.Descr
The FULL JOIN and the GROUP BY seem to be what I'm struggling most with. I've reviewed this SO answer and I understand how to execute a FULL JOIN on its own, but can't figure out how to integrate that into the larger overall query.
TYA for any answers.
Try this
using(var ctx = new Dbcontext())
{
var list = (
from cs in ctx.CLIENTSSUITS
join trust in ctx.TRUSTS on cs.CLIENT equals trust.CLIENT
join at in ctx.ADV_TYPES on at.CODE equals trust.AT into temp from temp.DefaultIfEmpty()
join tla1 in ctx.CLIENTADDRESSES on tla.SSN equals trust.SSN && tla.ID = 'L' into temp2 from subtla1 in temp2.DefaultIfEmpty()
join tla2 in ctx.CLIENTADDRESSES on tla2.SSN equals trust.SSN && tla2.ID = 'M' into temp3 from subtla2 in temp3.DefaultIfEmpty()
where (cs.PRIMARY = w && ?.SecondaryRole = x && cs.ID = y && cs.Rev = z && cs.DELETED = 0)
select new
{
FName = trust.FName,
MName = trust.MName,
LName = trust.LName
LAddress = tla.Address,
MAddress = tma.Address,
Descr = at.Descr
}).ToList();
}
//if the list contains the right result then you can easily group it with this code
var results = list.GroupBy(x => new {
x.FName, x.MName, x.LName, x.LAddress, x.MAddress, Descr
});

Incorrect values after SQL to LINQ convertion

I need to convert following SQL into LINQ
select
app.id,
app.name,
app.version,
s.application,
s.analysis,
s.behaviour,
(select count(ia.id)
from appInstalled ia
JOIN deviceUser ud ON ia.device_id = ud.device_id
where ia.app_id = app.id) as deviceCount,
max(alrt.alert_date)
from application app
left join score s on app.app_md5 = s.md5hash
left join alert alrt on app.id = alrt.app_id
where app.name like '%gpsnav%'
group by device;
This is what I've done so far
var appQuery = (from app in entities.applications
join score in entities.scores on app.app_md5 equals score.md5hash into appScore
join alrt in entities.alerts on app.id equals alrt.app_id into appAlerts
from s in appScore.DefaultIfEmpty()
from a in appAlerts.DefaultIfEmpty()
let deviceCount = (from iapp in entities.appInstalled
join ud in entities.deviceUser on iapp.device_id equals ud.device_id
where iapp.id == app.id
select iapp.id).Count()
where string.IsNullOrEmpty(searchTerm) || app.name.ToLower().Contains(searchTerm.ToLower())
select new
{
AppId = app.id,
AppName = app.name,
AppVersion = app.version,
AppScore = s.application,
Analysis = s.analysis,
Behavior = s.behaviour,
Devices = deviceCount,
AlertDate = a.alert_date
});
var grouped = from a in appQuery
group a by new
{
a.AppId,
a.AppName,
a.AppVersion,
a.AppScore,
a.Analysis,
a.Behavior,
a.Devices,
a.AlertDate
} into g
select new
{
g.Key.AppId,
g.Key.AppName,
g.Key.AppVersion,
g.Key.AppScore,
g.Key.Analysis,
g.Key.Behavior,
g.Key.Devices,
AlertDate = g.Max(x=>x.AlertDate)
};
The above LINQ works but the data is incorrect for Device and AlertDate. What I am missing in here? Also I am not getting max of AlertDate while grouping in LINQ.

combine three queries

How can I combine these 3 queries together and return them as datatable:
1:
var TDD = 0;
var queryTDD = (from x in db.GetAll<WMINO>()
join y in db.GetAll<WMCTM>()
on x.PO_ID equals y.Contract_ID
select new
{
TDD = x.Payable,
});
2:
Decimal TotalToDatePayable = 0;
TotalToDatePayable = ((from ori in db.GetAll<WMPORI>()
join ctm in db.GetAll<WMCTM>()
on ori.CTMSysID equals ctm.CTMSysID
select ori.ExB4Taxes).Sum());
3:
var query = from ctm in db.GetAll<WMCTM>()
join vnm in db.GetAll<WMVNM>()
on ctm.VendSysID equals vnm.VendSysID
where ctm.WONOs == workOrder && ctm.TransType == "Purchase Order"
select new
{
ctm.CTMSysID,
ctm.Contract_ID,
ctm.VNM_ID};`
any help is appreciated
Not possible with this because each query has different result and using different columns and condition....
There is no meaning in combining this queries.............

Categories