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();
Related
I have the follow SQL query
SELECT ob.PK_OBJETIVO,
ev.NM_EVENTO,
ifi.QT_NOTA_IMPACTO,
imi.QT_NOTA_IMPACTO,
ire.QT_NOTA_IMPACTO,
(ifi.QT_NOTA_IMPACTO + imi.QT_NOTA_IMPACTO + ire.QT_NOTA_IMPACTO)/3 AS
Media
FROM AVALIACAO_IMPACTO AS ai
INNER JOIN EVENTO AS EV ON ev.PK_EVENTO = ai.FK_AVALIACAO_IMPACTO_EVENTO
INNER JOIN OBJETIVO AS ob ON ob.PK_OBJETIVO =
ai.FK_AVALIACAO_IMPACTO_OBJETIVO
INNER JOIN IMPACTO_FINANCEIRO AS ifi ON ifi.PK_IMPACTO_FINANCEIRO =
ai.FK_AVALIACAO_IMPACTO_IMPACTO1
INNER JOIN IMPACTO_MISSAO AS imi ON IMI.PK_IMPACTO_MISSAO =
AI.FK_AVALIACAO_IMPACTO_IMPACTO2
INNER JOIN IMPACTO_REPUTACAO AS IRE ON IRE.PK_IMPACTO_REPUTACAO =
AI.FK_AVALIACAO_IMPACTO_IMPACTO3
WHERE ai.FK_AVALIACAO_IMPACTO_OBJETIVO IN
(SELECT OBJ.PK_OBJETIVO
FROM OBJETIVO AS OBJ
WHERE OBJ.FK_OBJETIVO_PROCESSO = 3)
I need to transform that query in a LINQ query, I tried that:
var queryImpactos = await _context.AvaliacaoImpacto
.Where(e => _context.Objetivo.Select(o =>
o.ProcessoID).Contains(planoRiscos.Auditoria.ProcessoID))
.Include(e => e.Evento).Include(e => e.Objetivo)
.Include(e => e.ImpactoFinanceiro).Include(e =>
e.ImpactoMissao).Include(e => e.ImpactoReputacao).ToListAsync();
"planoRiscos.Auditoria.ProcessoID" returns what it takes, the number 3 of the pure SQL query, but the query result is returning all the records in the AVALIACAO_IMPACTO table, however I only need the records where a FK_OBJETIVO in AVALIACAO_IMPACTO exists within the OBJETIVO table, where the FK_PROCESSO in OBJETIVO is equal to the passed parameter (planoRiscos.Auditoria.ProcessoID).
Tip: whenever you need to convert SQL query to a LINQ query, make the query syntax your first choice.
Try this:
var queryImpactos = from ai in AVALIACAO_IMPACTO
join
ev in EVENTO on ai.FK_AVALIACAO_IMPACTO_EVENTO equals ev.PK_EVENTO
join ob in OBJETIVO on ai.FK_AVALIACAO_IMPACTO_OBJETIVO equals ob.PK_OBJETIVO
join ifi in IMPACTO_FINANCEIRO on ai.FK_AVALIACAO_IMPACTO_IMPACTO1 equals ifi.PK_IMPACTO_FINANCEIRO
join imi in IMPACTO_MISSAO on ai.FK_AVALIACAO_IMPACTO_IMPACTO2 equals imi.PK_IMPACTO_MISSAO
join IRE in IMPACTO_REPUTACAO on ai.FK_AVALIACAO_IMPACTO_IMPACTO3 equals IRE.PK_IMPACTO_REPUTACAO
where (from obj in OBJETIVO where obj.FK_OBJETIVO_PROCESSO == 3 select obj.PK_OBJETIVO).Contains(ai.FK_AVALIACAO_IMPACTO_OBJETIVO)
select new
{
ob.PK_OBJETIVO,
ev.NM_EVENTO,
QT_NOTA_IMPACTO1 = ifi.QT_NOTA_IMPACTO,
QT_NOTA_IMPACTO2 = imi.QT_NOTA_IMPACTO,
QT_NOTA_IMPACTO3 = IRE.QT_NOTA_IMPACTO,
Media = (ifi.QT_NOTA_IMPACTO + imi.QT_NOTA_IMPACTO + IRE.QT_NOTA_IMPACTO) / 3
};
Hope it's what you're looking for!
I am trying to convert a SQL Command to Linq but gets the error 'Unable to process the type 'Anonymous type', because it has no known mapping to the value layer.'
SQL Code
SELECT ooe.id, parts.title, appro.totalAppro, allo.TotalAllotment, cost.total_cost, (CASE WHEN cost.total_cost IS NULL THEN (SELECT allo.TotalAllotment) ELSE (SELECT allo.TotalAllotment - cost.total_cost) END) AS unobligated
FROM pmTA_OoeGeneral AS ooe INNER JOIN
pmTA_Particulars AS parts ON ooe.particular_id = parts.id LEFT OUTER JOIN
pmTA_vwObligationRequestDetailsTotalCostByOoe AS cost ON ooe.id = cost.ooe_general_id
LEFT OUTER JOIN pmTA_vwTotalAllotmentGeneralFund AS allo ON ooe.id = allo.ooe_general_id
LEFT OUTER JOIN pmTA_vwTotalAppropriationGeneralFund AS appro ON ooe.id = appro.ooe_general_id
WHERE (ooe.year = #year) AND (ooe.project_category_id = #cat) and (ooe.type = #type) order by ooe.id
LINQ Code
var gvStatusGenOffices = (from a in db.iBudget_OoeGeneral
join b in db.iBudget_Particulars on a.ParticularID equals b.id
join c in obligationRequestDetailsTotalCostByOoe on a.id equals c.id
join d in totalAllotmentGeneralFund on a.id equals d.id
join e in totalAppropriationGeneralFund on a.id equals e.id
where a.YearID==year && a.ProjectID==cat && a.type==type
orderby a.id
select new
{
id = a.id,
title = b.title,
appro = e.totalAppro,
allo = d.totalAllo,
cost = c.totalCost,
unobligated = c.totalCost==null ? d.totalAllo : d.totalAllo - c.totalCost
}).ToList();
db.iBudget_OoeGeneral and db.iBudget_Particulars are model class in my project
obligationRequestDetailsTotalCostByOoe , totalAllotmentGeneralFund and totalAppropriationGeneralFund are variables with list values.
The question is what is causing this error? I tried looking the web for some answers but none was showing up.
UPDATE
var obligationRequestDetailsTotalCostByOoe = (from p in db.iBudget_ObligationRequestDetails
where p.ooe_general_id != null && p.is_approved == 1
group p by p.ooe_general_id into g
select g)
.AsEnumerable()
.Select(g => new {
id = g.Key,
totalCost = g.Sum(p => Convert.ToDouble(p.amount))
}).ToList();
Originally, obligationRequestDetailsTotalCostByOoe , totalAllotmentGeneralFund and totalAppropriationGeneralFund were Views in SQL Server. Since I was practicing how to code Linq, I didn't create a View and just made a var with list same with the original View Code in SQL.
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
I have below sql query which I want to convert into LINQ to obtain exactly same results and returned by below query
select *
from (
select distinct DocID
from UserViewDoc
where UserViewDoc.UVID in (102558)) a
left outer join
(
select distinct UserViewDoc.DocID
from UserViewDoc
inner join UserViewHeader on UserViewDoc.UVID = UserViewHeader.UVID
where UserViewDoc.UVID not in (102558)
and UserViewHeader.IsLock = 1) b on a.DocID = b.DocID
where b.DocID is null
)
What I have tried so far is below LINQ statement
var v = (from uvd in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>()
where IDs.Contains(uvd.UVID)
select new { uvd.DocID, uvd.UVID });
var c = ((from uvd in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>()
join uvh in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewHeader>() on uvd.UVID equals uvh.UVID
where !IDs.Contains(uvh.UVID) && uvh.IsLock == true
select new { uvd.DocID, uvd.UVID } ));
var d = (from id in v
join ids in c on id.UVID equals ids.UVID into vc
from sub in vc.DefaultIfEmpty()
where sub == null
select id);
The problem I am facing is running the SQL query is returning 30583 records and LINQ version of it is returning all of the 30613 records
I rewrote the query to be exactly like the sql query, i believe that this is the way:
var firstQuery = (from u in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>()
where IDs.Contains(u.UVID)
select u.DocID).Distinct();
var innerQuery = (from u in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewDoc>()
join uvh in this.ViewSelectorControl.LDReviewContext.GetTable<UserViewHeader>() on uvh.UVID equals u.UVID
where IDs.Contains(u.UIVD) == false
&& uvh.IsLock
select u.DocID).Distinct();
var resultQuery = from f in firstQuery
join i in innerQuery on i equals f into lout
from i in lout.DefaultIfEmpty()
where i == null
select f;
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