COUNT(DISTINCT *) in ef core 2.1 - c#

SELECT
e.EmpName,
me.RemarkNumber,
me.RemarkPeopleNumber
FROM
EmployeeInfo e
LEFT JOIN (
SELECT
COUNT(RemarkId) As RemarkNumber,
COUNT(DISTINCT MemberId) As RemarkPeopleNumber,
CreateUser
FROM
MemberRemark
WHERE
RemarkStatus = 0
GROUP BY
CreateUser
) AS me On e.EmpName = me.CreateUser
WHERE
BranchCode = '0000'
And [Status] = 0
How to convert it to LINQ?
from e in db.EmployeeInfo
join me in (
from memberRemarks in db.MemberRemark
where memberRemarks.RemarkStatus == 0
group memberRemarks by new
{
memberRemarks.CreateUser,
} into g
select new
{
RemarkNumber = g.Count(),
RemarkPeopleNumber = g.Select(m => m.MemberId).Distinct().Count(),
g.Key.CreateUser
}
) on new { e.EmpName } equals new { EmpName = me.CreateUser } into meJoin
from me in meJoin.DefaultIfEmpty()
where e.BranchCode == "0000" & &e.Status == 0
select new
{
e.EmpName,
me.RemarkNumber,
me.RemarkPeopleNumber
};
I got this error
RemarkPeopleNumber = g.Select(m=>m.MemberId).Distinct().Count(),
//error
Using asp.net core mvc 2.1 + ef core 2.1 + mssql

Perhaps if you broke the query up into pieces it would be handled better? Using my SQL to LINQ Recipe I would translate your SQL like this:
var ePart = from e in db.EmployeeInfo
where e.BranchCode == "0000" && e.Status == 0
select e;
var mrPart = from mr in db.MemberRemark
where mr.RemarkStatus == 0
group mr by mr.CreateUser into mrg
select new {
CreateUser = mrg.Key,
RemarkNumber = mrg.Count(),
RemarkPeopleNumber = mrg.Select(mr => mr.MemberId).Distinct().Count()
};
var ans = from e in ePart
join me in mrPart on e.EmpName equals me.CreateUser into mej
from me in mej
select new {
e.EmpName,
me.RemarkNumber,
me.RemarkPeopleNumber
};

Related

Show related records according to the Id from another Table

In my ASP.NET MVC application, I have created an HTML Table using the view model.
For this, I have written a query that shows only the data that ReOrderQty is !=0 and AvaQty is less than ReOrderQty.
List < RecognizedPartsViewModel > Reco = new List < RecognizedPartsViewModel > ();
var rData = (from i in db.InventoryMain
join p in db.PartCategory on i.PartCatogary equals p.Id
where i.ReOrderQty != 0 && i.AvaQty <= i.ReOrderQty && i.PartCatogary != 0
select new RecognizedPartsViewModel {
Id = i.Id,
PartNo = i.PartNo,
Description = i.PartDescription,
Model = i.PartModel,
AvaQty = i.AvaQty,
ReOrderQty = i.ReOrderQty,
PartCato = i.PartCatogary,
ABCD = i.A_B_C_D_Category
}).ToList();
So as so far, table data is showing according to the query.
There is another table where I store Orders according to the PartId. So I want to show that data on another column in the same HTML Table.
I can get those details by joining the join ord in db.OrderTable on i.Id equals ord.PartNo_Id
but when it does results only show the PartNumbers that only contains on the OrderTable only.
This is how I modified it as I mention.
List < RecognizedPartsViewModel > Reco = new List < RecognizedPartsViewModel > ();
var rData = (from i in db.InventoryMain
join p in db.PartCategory on i.PartCatogary equals p.Id
join ord in db.OrderTable on i.Id equals ord.PartNo_Id
where i.ReOrderQty != 0 && i.AvaQty <= i.ReOrderQty && i.PartCatogary != 0
select new RecognizedPartsViewModel {
Id = i.Id,
PartNo = i.PartNo,
Description = i.PartDescription,
Model = i.PartModel,
AvaQty = i.AvaQty,
ReOrderQty = i.ReOrderQty,
PartCato = i.PartCatogary,
ABCD = i.A_B_C_D_Category,
PastOrders = "Order Qty: " + ord.OrderQty
}).ToList();
So, when this does like I was said earlier not show every record, it shows only the record in the ordertable.
So how I can show those tables within the same view without losing my main requirement?
That would be
left outer join
var rData = (from i in db.InventoryMain
join p in db.PartCategory on i.PartCatogary equals p.Id
join ord in db.OrderTable on i.Id equals ord.PartNo_Id into leftjoin
from order in leftjoin.DefaultIfEmpty()
where i.ReOrderQty != 0 && i.AvaQty <= i.ReOrderQty && i.PartCatogary != 0
select new RecognizedPartsViewModel {
Id = i.Id,
PartNo = i.PartNo,
Description = i.PartDescription,
Model = i.PartModel,
AvaQty = i.AvaQty,
ReOrderQty = i.ReOrderQty,
PartCato = i.PartCatogary,
ABCD = i.A_B_C_D_Category,
PastOrders = "Order Qty: " + order?.OrderQty ?? string.Empty
}).ToList();
Reference: Perform left outer joins

Convert T-SQL statement into LINQ expression

i am quite new to linq and actually fighting to convert the following t-sql statement into an linq to sql or linq to entities expression:
SELECT TOP 1
vm.EventID,
vmm.VotingMatrixID,
PersonAcceptedCount = SUM( CAST( vmm.IsAccepted AS INT) )
FROM VotingMatrixMember vmm
JOIN VotingMatrix vm
ON vmm.VotingMatrixID = vm.ID
WHERE vm.EventID = 'abbe3077-24de-45d8-ac04-13dba97c1567'
AND vm.Deleted = 0
AND vmm.Deleted = 0
GROUP BY vm.EventID, vmm.VotingMatrixID
ORDER BY PersonAcceptedCount DESC
Try this, can not test
var firstItem = (
from vmm in db.VotingMatrixMember
join vm in db.VotingMatrix on vmm.VotingMatrixID equals vm.ID
where vm.EventID = "abbe3077-24de-45d8-ac04-13dba97c1567"
&& vm.Deleted = 0
&& vmm.Deleted = 0
group new {vm, vmm} by new {vm.EventID, vmm.VotingMatrixID} into gr
select new
{
EventID = gr.Key.EventID,
VotingMatrixID = gr.Key.VotingMatrixID,
PersonAcceptedCount = gr.Sum(x => Convert.ToInt32(x.IsAccepted))
}
into groupedItem
orderby groupedItem.PersonAcceptedCount descending
select groupedItem
).FirstOrDefault();
var query =
from vm in dataContext.VotingMatrices
where vm.EventId == eventId
where vm.Deleted == 0
from vmm in vm.VotingMatrixMembers
where vmm.Deleted == 0
group vmm by new { vm.EventId, vmm.VotingMatrixId } into g
select new
{
g.Key.EventId,
g.Key.VotingMatrixId,
PersonAcceptedCount: g.Select(x => Convert.ToInt32(x.IsAccepted)).Sum()
} into resultRow
order by resultRow.PersonAcceptedCount descending
select resultRow;
var row = query.FirstOrDefault();

translate sql to linq with Where and GroupBY

SQL:
SELECT
p.PipelineID
, MAX(PipelineJobStatus.CreatedTimeStamp)
, Client.ClientName
, FCO.NameFCO
, p.ProjectValueHr
, p.ProjectValueMoney
, p.CommentPipeline
, PipelineJobStatus.CreatedTimeSTamp
, p.ModifiedTimeStamp
, Employee.Name
, Employee.Surname
, JobStatus.JobStatusName
FROM (Pipeline p
LEFT OUTER JOIN PipelineJobStatus ON p.PipelineID = PipelineJobStatus.PipelineID)
INNER JOIN JobStatus ON (PipelineJobStatus.JobStatusID = JobStatus.JobStatusID)
LEFT OUTER JOIN Client ON (p.ClientID = Client.ClientID)
LEFT OUTER JOIN FCO ON (p.FCOID = FCO.FCOID)
LEFT OUTER JOIN Employee ON (p.CreatedBy = Employee.EmployeeD)
WHERE PipelineJobStatus.CreatedTimeStamp IN
(SELECT MAX(CreatedTimeStamp) FROM PipelineJobStatus GROUP BY PipelineID)
GROUP BY p.PipelineID
, Client.ClientName
, FCO.NameFCO
, p.ProjectValueHr
, p.ProjectValueMoney
, p.CommentPipeline
, PipelineJobStatus.CreatedTimeSTamp
, p.ModifiedTimeStamp
, Employee.Name
, Employee.Surname
, JobStatus.JobStatusName
I've tried LINQ:
from pjs in db.PipelineJobStatus
//.OrderByDescending(p=>p.CreatedTimeStamp)
//.DistinctBy(p => p.PipelineID)
//.FirstOrDefault()
from pipe in db.Pipelines
.Where(pipe => pipe.PipelineID == pjs.PipelineID).DefaultIfEmpty()
from status in db.JobStatus
.Where(statuses => statuses.JobStatusID == pjs.JobStatusID)
.DefaultIfEmpty()
from fco in db.FCOes
.Where(fcoes => fcoes.FCOID == pipe.FCOID)
from client in db.Clients
.Where(clients => clients.ClientID == pipe.ClientID)
//Where PipelineJobStatus.CreatedTimeStamp in (select max(CreatedTimeStamp) from PipelineJobStatus group by PipelineID)
.Where(pjs.CreatedTimeStamp in select Max(pjs.CreatedTimeStamp)from PipelineJobStatus group by)
group by { pipe.PipelineID } //group new
by new
{
status.JobStatusName,
pipe.PipelineID,
pipe.ClientID,
client.ClientName,
fco.NameFCO,
fco.FCOID,
pipe.Employee.Name,
pipe.Employee.Surname,
pipe.CommentPipeline,
pipe.CreatedBy,
pipe.CreatedTimeStamp,
pipe.ModifiedTimeStamp,
pipe.ProjectValueHr,
pipe.ProjectValueMoney
} into g
orderby g.Key.PipelineID descending
select new StatusPipelineMerge
{
PipelineID = g.Key.PipelineID,
ProjectValueHr = g.Key.ProjectValueHr,
ProjectValueMoney = g.Key.ProjectValueMoney,
CommentPipeline = g.Key.CommentPipeline,
ClientName = g.Key.ClientName,
FCOName = g.Key.NameFCO,
FCOID = g.Key.FCOID,
ClientID = g.Key.ClientID,
CreatedTimeStamp = g.Key.CreatedTimeStamp,
ModifiedTimeStamp = g.Key.ModifiedTimeStamp,
CreatedBy = g.Key.CreatedBy,
//CreatedNameSurname = g.Key.Employee.Name + " " + g.Key.Employee.Surname
JobStatusName = g.Key.JobStatusName
}
.Where() clause is underlined with red..
Where I am wrong?
P.S. SQL is working
I will change this chained tables, with joins, for now I just want to work.
Maybe store procedure is not lousy option here.

Turning a MySQL query in LINQ SQL

I'm trying to make a MySQL query in LINQ to SQL but I am with a doubt. How do I "Sum(0.5) as QtdeDias" in LINQ to SQL?
Query:
Select CL.NomeDeGuerra as Colaborador, '' as Gerente, 'Bloqueio' as Cliente, 'Bloqueio' as Frente,
Date_Format(A.DataReferencia, '%Y-%m-01 00:00:00') as Periodo, 'Bloqueio' as Atividade, Sum(0.5) as QtdeDias
From Agenda A
join Colaborador CL on (A.ColaboradorID = CL.ID)
Where CL.Socio = 0 and A.TipoAgenda = 2 and A.IsDeleted = 0 and CL.ID = 29
group by CL.NomeDeGuerra, Concat('BLOQUEIO-', A.Descricao), Date_Format(A.DataReferencia, '%Y/%m')
Linq to SQL:
var recursos = from a in this.Context.Agenda
join cl in this.Context.Colaborador on a.ColaboradorID equals cl.ID
where
cl.ID == colaboradorId
&& cl.Socio == 0
&& a.TipoAgenda == 2
&& !a.IsDeleted
group new { cl, a } by new { cl.NomeDeGuerra, a.Descricao, a.DataReferencia } into g
select new
{
FrenteProjetoID = 0,
Colaborador = g.Key.NomeDeGuerra,
Gerente = "",
Cliente = "Bloqueio",
Frente = "Bloqueio",
DataReferencia = g.Key.DataReferencia,
Atividade = "Bloqueio",
QtdeDias = (decimal)0.5 ???????
};
Thanks!
You can try using the grouping you've created.
select new
{
FrenteProjetoID = 0,
Colaborador = g.Key.NomeDeGuerra,
Gerente = "",
Cliente = "Bloqueio",
Frente = "Bloqueio",
DataReferencia = g.Key.DataReferencia,
Atividade = "Bloqueio",
QtdeDias = g.Sum(e => 0.5m)
};

c# Linq select join on select group by

I have this MS-SQL statement :
SELECT cv.id FROM ContactValue cv
INNER JOIN (
SELECT mainId, max(version) as v
FROM ContactValue
WHERE version <= $Version(int)
GROUP BY mainId
)
AS t ON t.mainId = cv.mainId AND t.v = cv.version
WHERE cv.contact_id = $ContactID(int)
AND cv.isActive = 1
ORDER BY sort'
and would like to make it in linq.
I did make above query divided into multiple queries witch performence is not fast.
Does it exist any linq to linq joining
My C# code :
var groupMax = from cv in db.ContactValue
where cv.contact_id == ContactID && cv.version <= Version
orderby cv.sort
group cv by cv.mainId into gcv
select new { mainID = gcv.Key, version = gcv.Max(cv => cv.version) };
foreach (var data in groupMax.ToList())
{
var Query = from cv in db.ContactValue
where cv.contact_id == ContactID && cv.mainId == data.mainID && cv.version == data.version && cv.isActive == true
select cv;
if (Query.Count() > 0)
{
ContactValue tmp = Query.First();
}
}
I would love to get all contacts with 1-2 queries not 1 query then for each contact another query...
Please help me !
Yes, Linq to SQL does have an inner join implemented:
var groupMax =
from cv in db.ContactValue
where cv.contact_id == ContactID && cv.version <= Version
orderby cv.sort
group cv by cv.mainId into gcv
select new { mainID = gcv.Key, version = gcv.Max(cv => cv.version) };
var res =
from cv in db.ContactValue
join gm in groupMax on cv.version equals gm.version
where cv.contact_id == ContactID && cv.isActive
orderby cv.version ascending /*for example*/
select cv
protected void rptPriceRachiveBind()
{
using (MyEntities ctx = new MyEntities())
{
var catRef = Convert.ToInt32(Request.QueryString["CategoryRef"]);
var prodCounts = (
from A in ctx.Products
join B in ctx.ProductPrices
on A.ProductId equals B.ProductRef
where A.CategoryRef == catRef
group A by new { A.Name,B.ProductRef } into catGp
select
new
{
catGp.Key.ProductRef,
catGp.Key.Name,
proIdCount = catGp.Count()
}).ToList();
Repeater1.DataSource = prodCounts;
Repeater1.DataBind();
}

Categories