Converting SQL to Linq in c# - c#

I am trying to convert some SQL Code to c# Linq:
SELECT Username, Count(Ticket.TicketId) as 'Tickets Completed'
FROM Ticket
INNER JOIN TicketStatus ON Ticket.TicketStatusID = TicketStatus.TicketStatusID
INNER JOIN Membership ON Ticket.CompletedBy = Membership.UserId
WHERE Ticket.ClosedDate >= #StartDate
and Ticket.ClosedDate <= #EndDate
GROUP BY Username
ORDER BY 'Tickets Completed' DESC
which displays
Paul 6
Mike 4
Donna 3
Elliot 2
I tried to use Linqer which made this more complicated and didnt return any results:
var query = from Ticket in data.Tickets
join Membership in data.Memberships on new { CompletedBy = Guid.Parse(Ticket.CompletedBy.ToString()) } equals new { CompletedBy = Membership.UserId }
where
Ticket.ClosedDate >= StartDate &&
Ticket.ClosedDate <= EndDate
group new { Membership, Ticket } by new
{
Membership.Username
} into g
orderby
"Tickets Completed" descending
select new
{
Username = g.Key.Username,
Completed = g.Count(p => p.Ticket.TicketID > 0)
};
Your help would be appreciated.
Thanks

Assuming CompletedBy and UserId columns are both uniqueidentifier in the database, you shouldn't need to do any type conversion.
var query = from t in db.ticket
join ts in db.ticketStatus
on t.TicketStatus.ID equals ts.TicketStatusID
join m in db.Membership
on t.CompletedBy equals m.UserId
where t.ClosedDate >= startDate
&& t.closedDate <= endDate
group t by m.UserName into tGroup
order by tGroup.Count(t=> t.TicketId) decending
select new {
UserName = tGroup.Key,
TicketCount = tGroup.Count()
};

Related

Linq query returns 0 count when join with related tables

I need to query a table and join related tables. A single query without joining another table returns the expected result. but once I join another table I get zero result.
The below query returns some results
var response = from o in context.Orders.Where(p => p.Start_Effective >= startDate && p.Start_Effective < endDate);
But once I join another table
var response = from o in context.Orders.Where(p => p.Start_Effective >= startDate && p.Start_Effective < endDate);
join v in context.Venue on o.Id equals v.Id
select new
{
Id = o.Id,
PointId = o.FromPointId,
VenueName = v.Name
};
I also try the below query and I still get zero result
var response = from o in context.Orders.Where(p => p.Start_Effective >= startDate && p.Start_Effective < endDate)
from v in context.Venue
where v.OrderId == o.Id
select new
{
Id = o.Id,
PointId = o.FromPointId,
VenueName = v.Name
};
I cant figure out why this is returning 0 result once I join table
If there is no record in Venue Table with OrderId, when inner join is used, no data returned and you should insert a record that has OrderId that exist in Order Table.
Another option is using left join.
By left join, if there is no OrderId in Venue Table, result was returned
try to use a left join, and add to list
var response = (from o in contextOrders
join v in context.Venue on o.Id equals v.Id into vj
from v in vj.DefaultIfEmpty()
where ( o.Start_Effective >= startDate && o.Start_Effective < endDate)
select new
{
Id = o.Id,
PointId = o.FromPointId,
VenueName = v.Name
}).ToList();

LINQ: join multiple Table Column using Linq and find aggregated sum from child table values

I'm using Linq (code-first approach) query to retrieve the data from DB and couldn't able to get similar result while using below linq query:
from msi in db.MainSaleInvoiceTbls
join dsi in db.DetialSaleInvoiceTbls on msi.Id equals dsi.MainSaleInvoiceId
join ca in db.CustomerAccounts on msi.CustomerId equals ca.Id
join cg in db.MiscLists on ca.CustomerGroupId equals cg.Id
where msi.IsActive == true && msi.CompanyId == UniversalInfo.UserCompany.Id && msi.MainSaleInvoiceDataType == MainSaleInvoiceType.SOInvoice
group msi by new { dsi,msi.Date,msi.FinancialVoucher,msi.SaleOrderPrefix,msi.SaleOrderNumber,msi.SalesId,ca.CustomerName,ca.AccountCode,cg.Name }
into mainSaleInvoice
from dx in mainSaleInvoice.DefaultIfEmpty()
// orderby main.Id
select new
{
Date = mainSaleInvoice.Key.Date,
Voucher = mainSaleInvoice.Key.FinancialVoucher,
InvoiceAccount = mainSaleInvoice.Key.AccountCode,
CustomerName = mainSaleInvoice.Key.CustomerName,
CustomerGroup = mainSaleInvoice.Key.Name,
Invoice = mainSaleInvoice.Key.SaleOrderPrefix + mainSaleInvoice.Key.SaleOrderNumber,
PurchaseOrder = mainSaleInvoice.Key.SalesId,
SalesTax = "",
InvoiceAmount = mainSaleInvoice.Sum(x => (Double)(mainSaleInvoice.Key.Quantity * mainSaleInvoice.Key.UnitPrice))
}).ToList()
In linq, i need to get shortdatetimeString() and sum() of (unitprice* quantity) from child table DetialSaleInvoiceTbls
being new in query writing, I don't know where and what I'm doing wrong. Any suggestions would be much appreciated.
var list=from msi in db.MainSaleInvoiceTbls
join dsi in db.DetialSaleInvoiceTbls on msi.Id equals dsi.MainSaleInvoiceId
join ca in db.CustomerAccounts on msi.CustomerId equals ca.Id
join cg in db.MiscLists on ca.CustomerGroupId equals cg.Id into a
where msi.IsActive == true && msi.CompanyId == UniversalInfo.UserCompany.Id
&& msi.MainSaleInvoiceDataType == MainSaleInvoiceType.SOInvoice
from cg in a.DefaultIfEmpty()
select new
{mainSaleInvoice.Date,
mainSaleInvoice.FinancialVoucher,mainSaleInvoice.AccountCode,
mainSaleInvoice.CustomerName,mainSaleInvoice.Name,
mainSaleInvoice.SaleOrderPrefix, mainSaleInvoice.SaleOrderNumber,
mainSaleInvoice.SalesId, }).sum(x=>x. (mainSaleInvoice.Quantity *
mainSaleInvoice.UnitPrice)).groupby msi new
{msi.Date,msi.FinancialVoucher,msi.SaleOrderPrefix,msi.SaleOrderNumber,
msi.SalesId};
Date = mainSaleInvoice.Date;
Voucher = mainSaleInvoice.FinancialVoucher;
InvoiceAccount = mainSaleInvoice.AccountCode;
CustomerName = mainSaleInvoice.CustomerName;
CustomerGroup = mainSaleInvoice.Name;
Invoice = mainSaleInvoice.SaleOrderPrefix +
mainSaleInvoice.SaleOrderNumber;
PurchaseOrder = mainSaleInvoice.SalesId;
SalesTax = "";
InvoiceAmount =list;

LINQ - Where, Group Sum

I have this SQL code:
select A.Recurso_Id, sum(case when B.cita_id is null then 0 else 1 end) as Total_Eventos, a.Recurso_Nombre, a.Recurso_Email,a.Recurso_Activo
from Agenda_Recurso a left join Agenda_Cita B
on A.Recurso_Id=B.Recurso_Id
where B.Cita_Fecha_Final > getdate()
group by A.Recurso_Id, a.Recurso_Nombre, a.Recurso_Email, a.Recurso_Activo
And, I need to traslate to LINQ, actually I have this code:
public List<Recurso> Cantidad_Eventos_Recurso(string pConexion, long pEmpresa, long pSucursal)
{
DateTime dt = DateTime.Now;
List<TRegAgendaCita> _LstCitas = MetodosEnLinea.Catalogo.AgendaEvento_Lista(pConexion, pSucursal);
List<TRegAgendaRecurso> _LstRecursos = MetodosEnLinea.Catalogo.AgendaRecurso_Lista(pConexion, pEmpresa);
if (_LstCitas == null)
return null;
List<Recurso> _ListaSelect = (from Recursos in _LstRecursos
join Citas in _LstCitas on Recursos.Id equals Citas.Recurso_Id
where Citas.Fecha_Final > dt
into cleft
select new Recurso()
{
Cantidad_Eventos = cleft.Where(x => x.Recurso_Id == Recursos.Id).Count(),
Nombre = Recursos.Nombre,
Email = Recursos.Email,
Activo = Recursos.Activo,
Id = Recursos.Id
})
.ToList();
return _ListaSelect;
}
But, in the section that I want to buy the final date with today, he tells me that he is wrong, he says:A query body must end with a select clause or a group clause. Somebody could help me?
The syntax for your query should look like this:
from Recursos in _LstRecursos
join Citas in _LstCitas.Where(c => c.Fecha_Final > dt) // notice the where moved here
on Recursos.Id equals Citas.Recurso_Id
into cleft
select new Recurso()
{
Cantidad_Eventos = cleft.Where(x => x.Recurso_Id == Recursos.Id).Count(),
Nombre = Recursos.Nombre,
Email = Recursos.Email,
Activo = Recursos.Activo,
Id = Recursos.Id
}
You can't put an into clause after where in query syntax. If you want query syntax you can use this, which is a little more verbose:
from Recursos in _LstRecursos
join Citas in
from c in _LstCitas
where c.Fecha_Final > dt
select c
on Recursos.Id equals Citas.Recurso_Id
into cleft
select new Recurso()
{
Cantidad_Eventos = cleft.Where(x => x.Recurso_Id == Recursos.Id).Count(),
Nombre = Recursos.Nombre,
Email = Recursos.Email,
Activo = Recursos.Activo,
Id = Recursos.Id
}

Linq record not in other table

i want to know how to select those record which is not in another table.
I have a query to show all the stock in a period of time
var query = (from stk in ie.stocks
join s in ie.staffs on stk.stk_createby equals s.stf_id
where stk.stk_createdate >= startDate &&
stk.stk_createdate <= endDate
select new
{
StockID = stk.stk_id,
RefNo = stk.stk_ref_id,
Weight = stk.stk_weight,
Grade = stk.stk_grade,
Remark = stk.stk_remark,
StaffName = s.stf_name
}).ToList();
And also i have another query to show all delivered stock.
var query2 = (from ol in ie.orderLists
join stk in ie.stocks on ol.ol_stockid equals stk.stk_id
join dl in ie.deliveries on ol.ol_dlyid equals dl.dly_id
join s in ie.staffs on stk.stk_createby equals s.stf_id
where dl.dly_delivery_date >= startDate &&
dl.dly_delivery_date <= endDate
select new
{
StockID = stk.stk_id,
RefN = stk.stk_ref_id,
Weight = stk.stk_weight,
Grade = stk.stk_grade,
Remark = stk.stk_remark,
StaffName = s.stf_name
}).ToList();
So what i want is to show the remain stock which is not deliver. How to exclude all stock in query2?
Try Except method.
ex)
var ret = query1.Except(query2);

SQL query to LINQ using group / sum / having

I've been trying to translate following query from SQL to LINQ, main purpose of my query is to find two or more transactions by the same Sender in which the amount's sum is >= 2000
SELECT t.TXN_SENDER_ID,
s.SEN_FIRSTNAME,
s.SEN_LASTNAME,
SUM(t.TXN_AMOUNT)
FROM TRANSACTIONS t
INNER JOIN SENDERS s ON s.SEN_ID = t.TXN_SENDER_ID
WHERE t.TXN_DATE BETWEEN Dateadd(YEAR, -3, Getdate()) AND Getdate()
GROUP BY t.SENDER_ID, s.SENDER_NAME, s.SENDER_LASTNAME
HAVING SUM(t.TXN_AMOUNT) > 2000
Here's what I've tried:
var query = from t in context.TRANSACTIONS
join s in context.SENDERS on t.TXN_SENDER_ID equals s.SEN_ID
group new { t, s } by new { t.TXN_SENDER_ID, s.SEN_FIRSTNAME, s.SEN_LASTNAME, t.TXN_AMOUNT } into gr
where (gr.Sum(x => x.t.TXN_AMOUNT) > 1000)
select new { gr.Key.TXN_AMOUNT, gr.Key.SEN_FIRSTNAME, gr.Key.SEN_LASTNAME };
Thanks in advance
OK, you haven't answered my question, but looking at your sql query you want to filter data on TXN_DATE. My best guess:
DateTime dtFrom = DateTime.Today.AddDays(-3);
DateTime dtTo = DateTime.Today;
var query = from t in context.TRANSACTIONS
.Where(tr=>tr.TXN_DATE>=dtFrom && tr.TXN_DATE<=dtTo)
join s in context.SENDERS on t.TXN_SENDER_ID equals s.SEN_ID
group new { t, s } by new { t.TXN_SENDER_ID, s.SEN_FIRSTNAME, s.SEN_LASTNAME, t.TXN_AMOUNT } into gr
where (gr.Sum(x => x.t.TXN_AMOUNT) >= 2000)
select new
{
gr.Key.TXN_SENDER_ID,
gr.Key.SEN_FIRSTNAME,
gr.Key.SEN_LASTNAME,
gr.Sum(a=>a.TXN_AMOUNT)
};

Categories