Good day to all,
I have the following problem
I have to convert the following query SQL to LINQ to SLQ or lambda expression:
SELECT T2.ID, SUM(T1.Importe) AS Importe, T3.ID, T3.Column_1,
T3.Column_2, T1.Column_3
FROM Tabla_1 T1
INNER JOIN Tabla_2 T2 on T1.ID = T2.ID
INNER JOIN Tabla_3 T3 on T2.ID = T3.ID
WHERE T1.ID in (LIST)
GROUP BY T2.ID, T3.ID, T3.Column_1, Column_2, T1.Column_3
where LIST is a List (12,15,18,19,...)
as performed in linq or lamnbda expression?
thks!
Here is the hint:
var result = ents.T1
.Where(x => list.Contains(x.Id))
.GroupBy(x => new
{
Id2 = x.T2.Id,
Id3 = x.T3.Id,
...
// etc group fields
})
.Select(x => new
{
Importe = x.Sum(i => i.Importe)
x.Key.Id2,
// other group fields
...
})
.ToArray();
I strongly suggest not to name columns and tables the way you did. Really)
I did not try, but it could look like that :
var result = (from t1 in dataContext.tabla_1
join t2 in dataContext.tabla_2 on t1.ID equals t2.ID
join t2 in dataContext.tabla_2 on t2.ID equals t3.ID
group t2 by t2.ID into g
where listIds.contains(t1.ID)
select new {g.ID, g.Sum(t => t.Importe), ...});
Related
I have this simple SQL:
SELECT name, value
FROM table1 t1, table2 t2
WHERE t1.id = t2.id
AND t1.id = 123
How do I convert it to LINQ in C#, so that the results are in Dictionary?
I'm guessing you are using Entity Framework?
Could you use RelationShips instead?
Or like this:
var query = from t1 in context.Table1
from t2 in context.Table2
where t1.Id == t2.Id
select new { t1.name, t2.value};
var result = query.ToList();
var dir = result.ToDictionary(x => x.name, x => x.value);
https://learn.microsoft.com/en-us/ef/core/querying/complex-query-operators
I am facing issue to apply Right Outer Join in LINQ. I am trying to build the similar query in LINQ by converting from SQL query.
My correct SQL query
select *
from Table1 t1
inner join Table2 t2 on t1.Id = t2.FID and t1.CID = 20
right outer join Table3 t3 on t1.GID = t3.GID
var result = from t1 in Table1
join t2 in Table2
on t1.ID equals t2.FID into gr1
where t1.CID = 20
join t3 in Table3
on t1.GID equals t3.GID into gr2
from t3 in gr2.DefaultIfEmpty()
select new Details (){
}
return result.ToList();
}
My LINQ query is not working as expected to SQL query.
This is also discussed here
how to make a right join using LINQ to SQL & C#
var RightJoin = from adds in dc.EmpresaAddendas
join cats in CatAddendas
on adds.IDAddenda equals cats.IDAddenda into joined
from cats in joined.DefaultIfEmpty()
select new
{
Id = cats.IDAddenda,
Description = cats.Descripcion
};
Try this:
var result = from t1 in Table1
join t2 in Table2
on new { id = t1.ID; cid = t1.CID } equals new { id = t2.FID: cid = 20} into gr1
join t3 in Table3
on t1.GID equals t3.GID into gr2
from t123 in gr2.DefaultIfEmpty()
select new Details (){
}
return result.ToList();
}
As you're discovered, most LINQ providers don't offer support for a right join. DefaultIfEmpty translates into a LEFT join. As a result, you need to flip the logic of your query around a bit to turn the right join into a left one.
As far as the actual syntax, I've had success adopting more of an ANSI-82 syntax rather than worrying about the into temp2 from temp3 in temp2 syntax. Something along the lines of:
var result =
from t3 in Table3
from t1 in Table1.Where(temp1 => temp1.GID == t3.GID).DefaultIfEmpty()
join t2 in Table2 on t1ID equals t2.FID
where t1.CID == 20
select new Details{};
I have a problem writing a LINQ query using CROSS JOIN on two tables, and subquery in the result.
I'll show you the SQL query that I made, and it is working in my PostgreSQL Server:
SELECT t2.id, t1.id,
(
SELECT COALESCE(avg(t3.value), -1)
FROM table3 t3
LEFT JOIN table4 t4 ON t4.id = t3.tag_id
LEFT JOIN table5 t5 ON t5.id = t4.device_id
LEFT JOIN table6 t6 ON t6.id = t4.system_id
WHERE t4.tag_type_id = 171 --TT Value
AND t1.id = ANY(t4.control_area)
AND t6.zone_id = t2.id
)
FROM table1 t1
CROSS JOIN table2 t2
ORDER BY t2.z_index,t1.d_index
And I try now to duplicate this query in EF Core code and this is what I got so far:
var ss = ctx.Table1.SelectMany(
t1 => ctx.Table2,
(t1, t2) => new
{
T1 = t1.Id,
T2 = t2.Id,
Value = ctx.Table3
.Include(s => s.Table4.Table5.Table6)
.Where(s => s.Table4.TagTypeId == 171
&& s.Table4.Table5.ControlArea.Any(a => a == t1.Id)
&& s.Table4.Table5.Table6.Zone == t2.Id)
}).ToList();
When I run this I get the following error:
Unable to cast object of type 'System.Linq.Expressions.MethodCallExpression2' to type
'System.Linq.Expressions.LambdaExpression'.
I'm not sure how can I accomplish this without using ctx.Database.ExecuteSqlRaw("SELECT ....");
Is there a way to do it?
Thanks in advance,
Julian
I was able to solve my problem. I'm posting this answer with hope that it will help others with similar problem. The solution is just to add .Average(s=>s.Value) to the end of the subquery.
Something like this:
var ss = ctx.Table1.SelectMany(
t1 => ctx.Table2,
(t1, t2) => new
{
T1 = t1.Id,
T2 = t2.Id,
Value = ctx.Table3
.Include(s => s.Table4.Table5.Table6)
.Where(s => s.Table4.TagTypeId == 171
&& s.Table4.Table5.ControlArea.Any(a => a == t1.Id)
&& s.Table4.Table5.Table6.Zone == t2.Id).Average(s=>s.Value)
}).ToList();
How can I convert this outer left join to LINQ?
SELECT * from table1 t1
left join table2 t2 on t1.code = t2.code AND t2.id ='xxxxx'
WHERE t1.someId = 2
I'm trying something like this:
from t1 in db.table1
join t2 in db.table2 on t1.Code equals t2.Code
into oj
from sub in oj.DefaultIfEmpty()
where t1.someId == 2
where (sub.id == 'xxxx')
but not all rows from left table are being returned. The where clauses i think are applied after the join.
var res=(from t1 in table1.Where(x=>x.someId==2)
join t2 in table2.Where(y=>y.id==xxxx)
on t1.code = t2.code
into r
from t3 in r.DefaultIfEmpty()
select new {t1,t3}).ToList();
What is an equivalent LINQ query to the following SQL query:
Select Id, Name
From Table1 tbl1
Where Id in ( Select Id From Table2)
You basically described an inner join with selection of rows from one table:
var result = from t1 in Table1
join t2 in Table2
on t1.Id equals t2.Id
select new{t1.Id, t1.Name};
Next SQL statement will be generated using EF and MS SQL:
SELECT t1.Id, t1.Name
FROM Table1 AS t1
INNER JOIN Table2 AS t2 ON t1.Id = t2.Id
Note, that if you are selecting non-unique items from Table2, you can potentially have duplicates in the result. Use next query to avoid this problem, cons: it loads all ids from Table2 into memory, pros: more time efficient. Checkout Felipes answer's, which is also quite good, but has it's own cons discussed in the comment section.
var table2Ids = new HashSet<int>(context.Table2.Select(t2 => t2.Id));
var result = context.Table1
.Where(t => table2Ids.Contains(t.Id))
.Select(t => new{t.Id, t.Name});
try using the Contains method:
var query = from c in db.Table1
where db.Table2.Select(x => x.Id).Contains(c.Id)
select new { c.Id, c.Name };
var result = query.ToList();