I have three tables. I have to retrieve the data using Linq statement. My three table names are A,B,C. I connected join for connecting two tables A and B based on the id's like:
select ol, fN, LN, ci, co
from member
join details
on member_id = details_id
where details_id in
(select contacts_id from contacts where
contacts_id1 = 1 and contacts_usr_id = 1)
I am able to write the query up to the where condition, how can I write the query for the inner while condition?
you can try this:
var idlist = (from tbl in table3
where tbl.usr_id == 1 && tbl.contacts_id == 1
select tbl.contacts_id ).ToList();
var x = from A in table1
from B in table2 where A.user_id == B.user_id
&& idlist.Contains(A.user_id)
select new { a = A.a, b = A.b, c = A.c, d = B.d, e = B.e };
check and let me know if that work.
Try flipping the query upside down. How about the following:
var query =
from t3 in table3
where t3.user_id = 1 && t3.contacts_id = 1
join t2 in table2 on t3.contacts_id equals t2.usr_id
join t1 in table1 on t2.usr_id equals t1.userid
select new {t2.a, t2.b, t2.c, t1.d, t1.e};
Related
How would I convert the subQuery select with distinct to TypeORM querybuilder? Thanks.
SELECT `time`, (case when `start` is NULL then 0 else 1 end) `is_reserved` FROM a left join (SELECT `time` FROM b join c on c.b_id = b.id WHERE b.date = '2022-04-20') MySchedule on MySchedule.time = a.time where a.is_use = 1
a table
time
is_use
b table
id
date
c table
b_id
time
You can first build the nested query and then left-join it to the main query:
import { getConnection } from 'typeorm';
// build the nested query
const nestedQuery = getConnection()
.createQueryBuilder(B, 'b').select('time')
.innerJoin(C, 'c.b_id = b.id')
.where(`b.date = '2022-04-20'`);
getConnection().createQueryBuilder(A, 'a')
.select([
'time',
])
.addSelect('(case when `start` is NULL then 0 else 1 end)', 'is_reserved')
// left join the nested query
.leftJoin(
`(${nestedQuery.getQuery()})`,
'MySchedule',
'MySchedule.time = a.time')
.where('a.is_use = 1')
.getMany();
Where A, B and C are TypeORM entities.
I am trying to convert below query in entity framework core but not able to access field in select query after apply group by.
Select ProdCatg.Category As [Category]
,Prod.FKProdCatgID As [FKProdCatgID]
,SUM(Dtl.Qty + LD.ProdConv1 + Trn.CashAmt ) As [DistributionRateValue]
From tblSalesInv_Dtl Dtl
Left Join tblSalesInv_Trn Trn on Trn.PKID=Dtl.FKID And Trn.FKSeriesID=Dtl.FKSeriesID
Left Join tblProdLot_Dtl LD on Dtl.FKLotID=LD.PKLotID And LD.FKProdID=Dtl.FKProdID
Left Join tblProd_Mas Prod ON PKProdID=Dtl.FKProdID
Left Join tblProdCatg_Mas ProdCatg On PKProdCatgID=Prod.FKProdCatgID
Where Trn.DraftMode=0
Group By Prod.FKProdCatgID,ProdCatg.Category
Order By Category
I am trying convert like this but but not able to access Dtl.Qty + LD.ProdConv1 + Trn.CashAmtfields
var result1 = (from dtl in _context.TblSalesInvDtl
join ser in lstSeries on dtl.FkseriesId equals ser
join trn in _context.TblSalesInvTrn on new { s1 = dtl.Fkid, s2 = ser } equals new { s1 = trn.Pkid, s2 = trn.FkseriesId }
join lot in _context.TblProdLotDtl on new { s1 = dtl.FklotId, s2 = dtl.FkprodId } equals new { s1 = lot.PklotId, s2 = lot.FkprodId }
join p in _context.TblProdMas on dtl.FkprodId equals p.PkprodId into pr
from Prod in pr.DefaultIfEmpty()
join pl in _context.TblProdMas on dtl.FklinkedProdId equals pl.PkprodId into plid
from ProdLinked in plid.DefaultIfEmpty()
join t in _context.TblTaxMas on dtl.FktaxId equals t.PktaxId into tid
from Tax in tid.DefaultIfEmpty()
join c in _context.TblProdCatgMas on Prod.FkprodCatgId equals c.PkprodCatgId into cid
from Catg in cid.DefaultIfEmpty()
where trn.EntryDate == Convert.ToDateTime("1-12-2018")
group Catg by new { Prod.FkprodCatgId, Catg.Category } into gb
//, dtl, lot, Prod
select new
{
CategoryName = gb.FirstOrDefault().Category,
DistributionRateValue = gb.Sum(a => (gb.Key.dtl.Qty + gb.Key.lot.ProdConv1+ gb.Key.lot.CashAmt)),
FKProdCatgID= gb.Key.Prod.FkprodCatgId,
}
).ToList();
can anybody help me how can I access multiple table fields in sum with groupby in entity framework core.
I have two tables table1 and table2. Each table contains a column with itemPrice. I need to add the two columns together.
The SQL query below returns the correct SUM.
SELECT SUM(item1+ item2) FROM
(select SUM(t1.itemPrice) item1 from table1 t1 WHERE t1.userid=='jonh') tableA
CROSS JOIN
(select SUM(t2.itemPrice) item2 from table2 t2 WHERE t1.userid=='jonh') tableB
I am not been lazy but the above query has so many SUM functions that I don't know where to start to write LINQ queries.
Can anyone help?
Ceci,
Hopefully this will give you what you want...
from f in (
from x in ( from t1 in Table1
where t1.Userid.Equals("John")
select new { Userid = t1.Userid }
).Distinct()
select new { item1 = ( from z in Table1
where z.Userid.Equals("John")
select z.ItemPrice ).Sum() ??0 ,
item2 = ( from z in Table2
where z.Userid.Equals("John")
select z.ItemPrice ).Sum() ??0 }
) select new { total = f.item1 + f.item2 }
In the case where there are no records for "john" in one table, it will bring back a 0 and sum up the other tables.
hope this helps.
Model:
return (from m in meterReadings
group m by new { date = m.ReadDate } into g
select new
{
ReadDate = g.Key.date.ToString("dd.MM.yyyy - HH:mm:ss"),
T1 = from t1 in g
where t1.Name == "T1"
select t1.Value.ToString("0,0.000"),
T2 = from t2 in g
where t2.Name == "T2"
select t2.Value.ToString("0,0.000"),
T3 = from t3 in g
where t3.Name == "T3"
select t3.Value.ToString("0,0.000"),
Total = from total in g
where total.Name == "Toplam"
select total.Value.ToString("0,0.000")
}).AsQueryable<object>();
Query
var table = MeterReadingManager.GetMeterReadingsPivot(meterReadings, 1);
//No Error (in title)
rows = table.OrderBy("ReadDate","desc").Skip((pageIndex) * pageSize).Take(pageSize)
//Error (in title)
rows = table.OrderBy("T1","desc").Skip((pageIndex) * pageSize).Take(pageSize)
When I order by ReadDate, It works. But When I try to order by other fields I get the error : At least one object must implement IComparable
Why I get this error? And How can I fix it?
If you want to sort a list of items of any type, the type must implement IComparable for the sort algorithm to be able to compare items. T1 is an IQueryable, whcih does not implement IComparable. I think you intended to create string values for T1, T2, and T3. If so, you should add FirstOrDefault() to each linq statement creating T1, etc.
Edit
(After your comment)
I mean this:
T1 = (from t1 in g
where t1.Name == "T1"
select t1.Value.ToString("0,0.000")).FirstOrDefault()
Now T1 is a string and, thus, it can be used in sorting.
You could try ThenByDescending:
var rows = table
.OrderByDescending(x => x.ReadDate).Skip((pageIndex) * pageSize).Take(pageSize)
.ThenByDescending(x => x.T1).Skip((pageIndex) * pageSize).Take(pageSize);
UPDATE:
You could use Reflection (a bit slower) if ordering by one field:
var tableInfo = table.GetType().GetProperty("T1");
var sortedRow = table.OrderByDescending(x => tableInfo.GetValue(x, null)).Skip((pageIndex) * pageSize).Take(pageSize);
Hi guys i need to replicate this SQL query in Linq to Entity
select * from Subscriber a
inner join User b on a.UserId = b.Id
where b.Username = 'Name'
May be some one may help.
Try this:
var query = from s in context.Subscribers.Include("User")
where s.User.Username == "Name"
select s;
This suppose that Subscriber has navigation property User referencing the user instance.
If you wan to use join (which is not needed) you can use this for inner join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id
where u.Username == "Name"
select new
{
Subscriber = s,
User = u
};
or this for left outer join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id into x
where u.Username == "Name"
from y in x.DefaultIfEmpty()
select new
{
Subscriber = s
User = y,
};