Convert SQL to Linq select in where - sql

I have three table below:
TABLE_PRODUCT (IdProduct, ProductName, ProductUnit)
TABLE_STORE_HOUSE (IdContain, IdProduct, ProductNumber, TimeInput)
TABLE_SELL (IdSell, IdContain, ProductNumberSell, TimeSell)
Current, How to using LinQ query get TABLE_STORE_HOUSE.IdProduct witch condition TABLE_STORE_HOUSE.ProductNumber - Sum(TABLE_SELL.ProductNumberSell) > 0 and TABLE_STORE_HOUSE.TimeInput is smallest
Help me convert Sql to Linq..............
select top 1 IdContain
from
TABLE_STORE_HOUSE
where IdProduct = '6'
and
ProductNumber - (select sum(ProductNumber)
from TABLE_SELL
Where TABLE_SELL.IdContain = IdContain)> 0
order by TimeInput desc;

Can you try this?
from t in TABLE_STORE_HOUSEs
let TSell = (
from s in TABLE_SELLs
where s.IdContain == t.IdContain
orderby s.ProductNumber
select new {
s.ProductNumber
}
)
where t.IdProduct == 6 && (t.ProductNumber - TSell.Sum(si => si.ProductNumber)) > 0
select new { t.IdContain }
for top 1 you can use Take() function.

Related

Covert SQL to Linq Query

I am doing my final year's project, I am new to linq as well. I have an SQL statement which i want to convert it to linq. I am currently using .net core.
I will greatly appreciate any help ,
WITH
cte_company (CompanyID, CompanyName, CompanyNumber, IncorporatedDate, TOTAL_YEARS) AS
(
SELECT
CompanyID,
CompanyName,
CompanyNumber,
IncorporatedDate,
DATEDIFF(YEAR, IncorporatedDate, CURRENT_TIMESTAMP) AS TOTAL_YEARS
FROM tbl_Company
)
SELECT
cte_company.CompanyID,
CompanyName,
CompanyNumber,
IncorporatedDate,
TOTAL_YEARS,
CASE
WHEN TOTAL_YEARS > 1 THEN (SELECT
DATEADD(MONTH, 9, MAX(TaxReturnDate))
FROM tbl_Tax
WHERE cte_company.CompanyID = tbl_Tax.CompanyID)
ELSE DATEADD(MONTH, 21, IncorporatedDate)
END AS TaxDate
FROM cte_company
I tried :
var result = (from comp in this.AccountDB.TblCompanies
where comp.CompanyStatus == true && comp.UserName == username
join tax in this.AccountDB.TblTaxes
on comp.CompanyId equals tax.CompanyId
orderby tax.TaxReturnDate descending
select new CompanyTaxInfo
{
CompanyName = comp.CompanyName,
CompanyID = comp.CompanyId,
CompanyNumber = comp.CompanyNumber,
})
.ToList();
As far as I can tell, the value read from tbl_tax is constant, which means it can be reduced to this:
var taxReturnDate = tbl_tax.Max(tx=>tx.TaxReturnDate).AddMonths(9);
var result = from c in tbl_Company
let TotalYears = (DateTime.Now - c.IncorporatedDate).Days / 365
select new
{
CompanyID = c.CompanyID,
c.CompanyName,
c.CompanyNumber,
c.IncorporatedDate,
TotalYears,
TaxDate = TotalYears > 1 ? taxReturnDate : c.IncorporatedDate.AddMonth(9)
}
You could still use your SQL with EF and still get the same result
for example if you create a stored procedure for your SQL
you could call it as the following
var result = await dbContext.<Your-Result-set>.FromSqlInterpolated(#$"[dbo].[Your-Procedure-Name]
{your-parameter1}
,{your-parameterN}
").ToListAsync();

How can convert SQL to lambda or LINQ

How can I convert below SQL to lambda or LINQ?
with cte
as (select * from test1
union all
select * from test2)
select * from cte
union all
select sum(columnA),sum(columnB),sum(columnC) from cte
In Linq UNION ALL is .Concat(), so:
var cte = test1.Concat(test2);
var sums = new MyModel
{
columnA = cte.Sum(c => c.columnA),
columnB = cte.Sum(c => c.columnB),
columnC = cte.Sum(c => c.columnC),
}
return cte.Concat(IEnumerable.Repeat(sums, 1));
You must remember that test1 and test2 must be type MyModel and MyModel contains only columnA, columnB and columnC.
I put two tables together in one datagridvie but in the last row of datagridview I need the total for both tables in the country, I can do one row in total for one table and another row for the other table I also don't need it, like I can only have one line with the total of both tables.
DataContex db = new DataContex();
var query = (
from v1 in db.View1
where shf.Date >= dpDate.Value && shf.Date <= dpDate1.Value
select new
{
v1.Name,
v1.Date,
v1.Quality,
v1.Rat,
v1.Total
}
).Concat
(
from v2 in db.View2
where f.Date >= dpDate.Value && f.Date <= dpDate1.Value
select new
{
v2.Name,
v2.Date,
v2.Quality,
v2.Rat,
v2.Total
}
).Concat
(from View2 in
(from v2 in db.View2
where v2.Date >= dpDate.Value && sh.Date <= dpDate1.Value
select new
{
v2.Name,
v2.Date,
v2.Quality,
v2.Rate,
v2.Total
})
group v2 by new { v2.NRFA } into g
select new
{
Name = "Total:",
Date = dpDate1.Value,
Quality = (decimal?)g.Sum(p => p.Quality),
Rate = (decimal?)g.Sum(p => p.Rate),
Total = (decimal?)g.Sum(p => p.Total)
}
);
Blockquote

select distinct out of three column connectiontable

I have a ef connection table with 3 columns in it. I want to select distinct value out of two of them.
I want to select distinct rows orderby ResourceId and MetaDataId.
So i want it to return row (1, 3 and 4) in this case.
Ive tried this:
ctx.ResourceMetas.Where(a => a.ResourceId == resourceid).Distinct()});
But obviously this gets the distinct values out of all three. Can i somehow choose to get distinct out of just the two?
You may group by your distinct values and then get the max or min of the leftovers.
In your case that you only have one more field you could do it like:
ctx.ResourceMetas
.GroupBy(x=>new{x.ResourceId, x.MetaDataId})
.Select
(
x=>new
{
MetaListId = x.Min(m=>m.MetaListId ),
ResourceId = x.Key.ResourceId,
MetaDataId = x.Key.MetaDataId
}
)
.Where(a => a.ResourceId == resourceid)
But in a scenario that you would like the distinct values of 2 fields out of more than three then you would have to do it like:
ctx.ResourceMetas
.GroupBy(x=>new{x.ResourceId, x.MetaDataId})
.Select
(
x=>new
{
MetaListId = x.Where(i=>i.MetaListId == x.Min(m=>m.MetaListId)).FirstOrDefault().MetaListId ,
OtherField = x.Where(i=>i.MetaListId == x.Min(m=>m.MetaListId)).FirstOrDefault().OtherField ,
ResourceId = x.Key.ResourceId,
MetaDataId = x.Key.MetaDataId
}
)
.Where(a => a.ResourceId == resourceid)

Nested selects in LINQ expression, how to?

I don't know how to work with nested selects in LINQ.
How could I convert this SQl expression to LINQ?
Select i.ID, i.Impression,
(Select COUNT(ImpressionsId)
from DiaryImpressions
where DiaryPostsId = '2' AND ImpressionsId = i.ID) as Num from Impressions i
Seriously? DiaryPostsId is a string? Oh well...
from i in context.Impressions
select new {
i.ID,
i.Impressions,
Num = (from d in context.DiaryImpressions
where d.DiaryPostsId == "2"
&& d.ImpressionsId == i.ID
select d).Count()
}
from ...
select new {
i.Id,
i.Impression,
Count = context.DiaryImpressions.Count(d => d.DiaryPostsId == 2 && d.ImpressionsId == i.Id)
}
If you map your objects properly, you can use child relations directly:
Count = i.DiaryImpressions.Count(d => d.DiaryPostsId == 2)

Need Linq translation for the following SQL Query

select colId,
colTaskType,
MaxID
from tblTaskType
join (
select tblCheckList.colTaskTypeID,
max(colItemNumber) MaxID
from tblCheckList
group by colTaskTypeID
) x on coltaskTypeID = tblTaskType.colID
Assuming you are using linq-to-sql and have the two tables in a datacontext.
The more or less exact translation would be:
var maxChecks = from checks in DataContext.tblChecklist
group checks by checks.colTaskTypeID into g
select new { colTaskTypeID, max = g.Group.Max(x => x.colItemNumber) };
var result = from t in DataContext.tblTaskType
join c in maxChecks on t.colTaskTypeID equals c.colTaskTypeID
select new { t.colId, t.colTaskTypeID, c.max };
But you could try:
var result = from t in DataContext.tblTaskType
select new {
t.colId,
t.colTaskTypeID,
Max = (from c in DataContext.tblChecklist
where c.colTaskTypeID == t.colTaskTypeID
select c.colItemNumber).Max() };