Why don't my SQL results match my Linq results? - c#

When I run this Query in SQL I get what I want:
SELECT Auckland_Park.Formative.[Formative Name]
FROM Auckland_Park.LearningUnit
INNER JOIN Auckland_Park.Formative
ON Auckland_Park.LearningUnit.ID = Auckland_Park.Formative.FK_LU
INNER JOIN Auckland_Park.Reference
INNER JOIN Auckland_Park.Course
ON Auckland_Park.Reference.FK_Course = Auckland_Park.Course.ID
ON Auckland_Park.LearningUnit.ID = Auckland_Park.Reference.FK_LU
WHERE Auckland_Park.Course.Name = 'BI'
My result:
Querying SQL Build
Report Develop
Java App Develop
Andriod App Set up
SharePoint Server
But when I work with my C# app I'm using LINQ to SQL, my LINQ Query looks like this:
//LINQ Query to fill Foramtive Name ComboBox
CTUDataContext data = new CTUDataContext();
var course = (from r in data.LearningUnits
join a in data.Formatives
on r.ID equals a.FK_LU
join f in data.References
on r.ID equals f.FK_LU
join g in data.Courses
on f.FK_LU equals g.ID
where g.Name == ("BI")
select new
{
formativeName = a.Formative_Name,
ID = a.ID
}
).ToList();
txtFormativeName.ItemsSource = course;
txtFormativeName.DisplayMemberPath = "formativeName";
txtFormativeName.SelectedValuePath = "ID";
It seems the same, but I'm not getting the same result that I'm getting with the SQL Query above.

//LINQ Query to fill Foramtive Name ComboBox
CTUDataContext data = new CTUDataContext();
var course = (from r in data.LearningUnits
join a in data.Formatives
on r.ID equals a.FK_LU
join f in data.References
on r.ID equals f.FK_LU
join g in data.Courses
on f.FK_LU equals g.ID
where g.Name == ("BI")
select new
{
formativeName = a.Formative_Name,
ID = a.ID
}
).ToList();
txtFormativeName.ItemsSource = course;
txtFormativeName.DisplayMemberPath = "formativeName";
txtFormativeName.SelectedValuePath = "ID";
ANSWER:
on f.FK_LU equals g.ID
f.FK_LU
must be replaced with
f.FK_Course

Related

Need help on Linq-to-SQL query (maybe nested query?)

I am asking for your help regarding a linq query to SQL.
Here is a part of the diagram of my database: https://imgur.com/xFBUm3q
My problem is in the following relationship: tbl_607_bottle and tbl_607_gaz_reporting, I can have several reportings for a bottle but reporting can only have one bottle.
I do this request but it's not satisfying.
var GazReportingWizardViewModel =
(from gr in db.tbl_607_gaz_reporting
join a in db.tbl_607_actors on gr.FK_ID_actors equals a.id
join bo in db.tbl_607_bottle on gr.FK_ID_bottle equals bo.ID
join loc in db.tbl_607_location on bo.FK_ID_location equals loc.ID
join cc in db.tbl_607_conformity_certificate on bo.FK_ID_conformity_certificate equals cc.ID
join j in db.tbl_607_join_bottle_gaz on bo.ID equals j.FK_ID_bottle
join g in db.tbl_607_gaz on j.FK_ID_gaz equals g.ID
join od in db.tbl_607_order_details on g.FK_ID_order_details equals od.ID
where loc.ID == Process
select new GazReportingWizardViewModel
{
bottle_conti_number = bo.bottle_conti_number,
pressure_value = gr.pressure_value,
reporting_date = gr.reporting_date,
first_name = gr.tbl_607_actors.first_name,
last_name = gr.tbl_607_actors.last_name,
expiration_date = cc.expiration_date,
content = od.content_comments
}).Distinct()
.OrderBy(t => t.reporting_date)
.ToList();
I want the last report on each bottle but it return all reports on each bottle.
Would you have an idea of ​​the solution?
Thank you for your time
Thank you so much!
I persisted in trying to solve the problem in a single query when the solution was so simple.
var GazReportingWizardViewModel = (from gr in db.tbl_607_gaz_reporting
join a in db.tbl_607_actors on gr.FK_ID_actors equals a.id
join bo in db.tbl_607_bottle on gr.FK_ID_bottle equals bo.ID
join loc in db.tbl_607_location on bo.FK_ID_location equals loc.ID
join cc in db.tbl_607_conformity_certificate on bo.FK_ID_conformity_certificate equals cc.ID
join j in db.tbl_607_join_bottle_gaz on bo.ID equals j.FK_ID_bottle
join g in db.tbl_607_gaz on j.FK_ID_gaz equals g.ID
join od in db.tbl_607_order_details on g.FK_ID_order_details equals od.ID
where loc.ID == Process
select new GazReportingWizardViewModel
{
bottle_conti_number = bo.bottle_conti_number,
pressure_value = gr.pressure_value,
reporting_date = gr.reporting_date,
first_name = gr.tbl_607_actors.first_name,
last_name = gr.tbl_607_actors.last_name,
expiration_date = cc.expiration_date,
content = od.content_comments
}).ToList();
var res = from element in GazReportingWizardViewModel
group element by element.bottle_conti_number
into groups
select groups.OrderByDescending(p => p.reporting_date).First();

Complicated SQL query to Linq

I need to convert the following complicated sql query to Linq in C#:
Select Empleador.NombreComercial as Empresa,
Vacante.Puesto as Vacante,
Vacante.Actividades,
COUNT(Vacante.CveVacante) as Visitas
from Vacante
LEFT JOIN Empleador on Empleador.CveEmpleador=Vacante.CveEmpleador
LEFT JOIN VisitaVacante on Vacante.CveVacante = VisitaVacante.CveVacante
GROUP BY Empleador.NombreComercial,Vacante.Puesto, Vacante.Actividades,
Vacante.CveVacante HAVING COUNT(*) > 1 ORDER BY Visitas DESC
For the moment I already have the following:
var Visitas = (from tvacante in db.VacanteT
join tEmpleador in db.EmpleadorT on tvacante.CveEmpleador equals tEmpleador.CveEmpleador
join tVisitaVacante in db.VisitaVacanteT on tvacante.CveVacante equals tVisitaVacante.CveVacante
select new
{
Empresa = tEmpleador.NombreComercial,
Vacante = tvacante.Puesto,
tvacante.Actividades,
Visitas = tvacante.CveVacante
}).GroupBy( );
How can I add the COUNT(Vacante.CveVacante) as Visitas and also the
GROUP BY Empleador.NombreComercial,Vacante.Puesto, Vacante.Actividades,
Vacante.CveVacante HAVING COUNT(*) > 1 ORDER BY Visitas DESC
to my linq query? I can't find information about how to complete this. The tables are tvacante, templeador, and tvisitaVacante.
Try this:
var Visitas =(from tvacante in db.VacanteT
join tEmpleador in db.EmpleadorT on tvacante.CveEmpleador equals tEmpleador.CveEmpleador
join tVisitaVacante in db.VisitaVacanteT on tvacante.CveVacante equals tVisitaVacante.CveVacante
group new{tEmpleador.NombreComercial,tvacante.Puesto, tvacante.Actividades} by new {tEmpleador.NombreComercial,tvacante.Puesto, tvacante.Actividades} into g
where g.Count()>1
select new
{
Empresa = g.Key.tEmpleador.NombreComercial,
Vacante = g.Key.tvacante.Puesto,
Actividades= g.Key.tvacante.Actividades,
Visitas = g.Count()
}).OrderByDescending(e=>e.Visitas);
If you want to do it using only linq query syntax and not merging both syntax then you could also do this:
var Visitas = from tvacante in db.VacanteT
join tEmpleador in db.EmpleadorT on tvacante.CveEmpleador equals tEmpleador.CveEmpleador
join tVisitaVacante in db.VisitaVacanteT on tvacante.CveVacante equals tVisitaVacante.CveVacante
group new{tEmpleador.NombreComercial,tvacante.Puesto, tvacante.Actividades} by new {tEmpleador.NombreComercial,tvacante.Puesto, tvacante.Actividades} into g
where g.Count()>1
orderby g.Count() descending
select new
{
Empresa = g.Key.tEmpleador.NombreComercial,
Vacante = g.Key.tvacante.Puesto,
Actividades= g.Key.tvacante.Actividades,
Visitas = g.Count()
};

How to write LINQ for multiple joins involving self join?

I am trying to translate the following query with self join to a LINQ expression.
select r2.* from depends d
join request r on d.DESC =r.DESC
join request r2 on d.ID=r2.ID
and d.TYPE ='sometype'
where r.ID= 12345
How can I correct the following LINQ query to match the correct SQL query above?
var result = (from d in depends
join r in request on d.DESC equals r.DESC
join r2 in request on d.ID == r2.ID && d.TYPE == incomingType.ToString()
where r.ID == incomingId
select r2).AsEnumerable();
Why don't you simple use a Where clause if your incomingType is fixed?
Also there is syntax for multiple join conditions, as shown here: LINQ Joining in C# with multiple conditions
E.g.:
var result = (from d in depends
where d.TYPE == incomingType.ToString()
join r in request on
new { ID = r.ID, desc = r.DESC }
equals
new { ID = d.ID, desc = d.DESC }
where r.ID == incomingId
select r).AsEnumerable();
If your incomingType is not actually fixed, and it gets its value from the depends table, you can just add a third parameter to the join condition, e.g.
var result = (from d in depends
where d.TYPE == incomingType.ToString()
join r in request on
new { ID = r.ID, desc = r.DESC, type = r.someType1 }
equals
new { ID = d.ID, desc = d.DESC, type = d.someType2 }
where r.ID == incomingId
select r).AsEnumerable();

SQL query into LINQ in asp.net mvc

Please anyone can help me to write this sql query into Linq. i have tried..
this is my sql query
select o.OrderID,o.Nature,o.Date,od.TotalPrice,os.OrderStatus,lo.FirstName,lo.EmailAddress,lo.PhoneNumber
from [dbo].[Order] o
inner join [dbo].[tbl_OrderDetails] od on od.OrderID = o.OrderID
inner join [dbo].[tbl_OrderHistory] oh on oh.OrderID = o.OrderID
inner join [dbo].[tbl_Login] lo on o.UserID = lo.UserID
inner join dbo.tbl_OrderStatus os on oh.OrderStatusID= os.OrderStatusID
group by o.OrderID,o.Nature,od.TotalPrice,o.Date,os.OrderStatus,lo.FirstName,lo.EmailAddress,lo.PhoneNumber
and this is my try
public override orderDetailModel orderDetails(int id)
{
var results = from o in obj.Orders
join od in obj.tbl_OrderDetails on o.OrderID equals od.OrderID
join oh in obj.tbl_OrderHistory on o.OrderID equals oh.OrderID
join l in obj.tbl_Login on o.UserID equals l.UserID
join os in obj.tbl_OrderStatus on oh.OrderStatusID equals os.OrderStatusID
where (od.OrderID == id)
group o by new { o.Nature, o.OrderID } into
select new orderDetailModel
{
OrderID = o.OrderID,
OrderStatus = os.OrderStatus,
Date = o.Date,
DeliveryNature = o.Nature,
EmailAddress = l.EmailAddress,
FirstName = l.FirstName,
PhoneNumber = l.PhoneNumber,
TotalPrice = od.TotalPrice
};
//group o by new {o.OrderID};
orderDetailModel data = (orderDetailModel)results.FirstOrDefault();
return data;
}
but this is wrong query its not working fine please help me
You need to correct the group by clause, like you have in the SQL query like this:-
group new { o, l } by new { o.OrderID,o.Nature,od.TotalPrice,o.Date,os.OrderStatus,
l.FirstName, l.EmailAddress,l.PhoneNumber } into g
select new orderDetailModel
{
OrderID = g.Key.OrderID,
OrderStatus = g.Key.OrderStatus,
Date = g.Key.Date,
..and so on
};
Since you need the grouping on two tables Order & tbl_Login you will have to first project them as anonymous type group new { o, l } then specify all the groupings and finally while projecting use Key to get the respective items.
I guess that actually, also the SQL query is not correct.
I would simply use a SELECT DISTINCT ... instead of Grouping all the columns.
Anyway, first thing to do:
Check if databases is designed correctly. As far as i can see, if you're joining the table with their Ids, i don't understand why you need to group all the data. If you have duplicates, maybe the error is in the Database design.
If you can't change your Database, or you are happy with it, then use the following LINQ approach:
var distinctKeys = allOrderDetails.Select(o => new { o.OrderID, o.Nature, o.TotalPrice, o.Date,o.OrderStatus,o.FirstName, o.EmailAddress,o.PhoneNumber }).Distinct();
var joined = from e in allOrderDetails
join d in distinctKeys
on new { o.OrderID, o.Nature,o.TotalPrice, o.Date,o.OrderStatus, o.FirstName, o.EmailAddress, o.PhoneNumber } equals d select e;
joined.ToList(); // gives you the distinct/grouped list

Can't access the fields of non-grouping tables in linq

I'm trying to join few tables using LINQ and retrieve a data set. But my problem is when I group the tables, I cannot access the fields of the non grouped tables in the LINQ query. here is my sample code block. Please help
var query = from sb in db.Surfboards
join csb in db.CustomerSurfBoards on sb.SurfBoardID equals csb.SurfBoardID
join c in db.Customers on csb.CustomerID equals c.CustomerID
where c.IsActive
group new { sb,csb} by new {sb.ID, csb.ComponentId} into g
select new ReportModel()
{
ReceivedDate = g.First().Name,
Number = c.First().Number <------- this cannot be accessed
}
what I'm trying to achieve is something like this
select sb.Id, max(c.Number), cbs.Id from Surfboards as sb
inner join CustomerSurfBoards as cbs on sb.SurfBoardID = csb.SurfBoardID
inner join Customers as c on csb.CustomerID = c.CustomerID
group by sb.Id, csb.ComponentId
Try this:
var query = from sb in db.Surfboards
join csb in db.CustomerSurfBoards on sb.SurfBoardID equals csb.SurfBoardID
join c in db.Customers on csb.CustomerID equals c.CustomerID
where c.IsActive
select new {sb.id, c.number, cbs.componentid} into tmp
from t in tmp
group t by new {t.ID, t.ComponentId} into g
select new
{
g.Key.id, g.Key.componentid, number = g.Select(n=>n.number).OrderByDescending().FirstOrDefault()
}

Categories