Linq record not in other table - c#

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);

Related

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;

How to display data in a chart from database?

I'm trying to display the amount of sold shoes in a chart.
I have four tables such as tblCategory, tblProduct, tblTransaction and tblTransactionItem.
I have three categories (MenShose, WomanShose, and KiddsShose as you see in the picture).
On the X-axis I want to display the category name and shose size like for example Wemanshose-35 there "WomenShe is categoryName and 35 is the size of the shose."
I tried this but it is giving me the wrong result.
public DisplaySales()
{
InitializeComponent();
chart1.Series.Clear();
var series = chart1.Series.Add("Series1");
series.XValueMember = "ProduktId";
series.YValueMembers = "TolatlSold";
series.Name = "Shose";
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
chart1.Series["Shose"].IsValueShownAsLabel = true;
series.CustomProperties = "LabelStyle=Left";
ShowTodaysSoldProduct();
}
// And here is what I'm trying but it shows me the wrong result. Please Help!
private void ShowTodaysSoldProduct()
{
using (Db db = new Db())
{
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
var result = (from tr in db.TransactionItems
join t in db.Transactions on tr.TransactionId equals t.TransactionId
//join p in db.Products on tr.ProductId equals p.ProductId
join c in db.Categories on tr.CategoryId equals c.CategoryId
where t.TransactionDate >= today && t.TransactionDate < tomorrow
group tr by tr.categories.CategoryName into g
select new ProductSaled
{
ProduktId = g.Key, // Before g.Key I want to display CategoryName too
TolatlSold = g.Count()
}).ToList();
chart1.DataSource = result;
chart1.DataBind();
chart1.Show();
}
}

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
}

Converting SQL to Linq in 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()
};

How to get data which has Max Date in linq

Here is a linq query, and the table "Timesheet_Log" has DT_CR Column with type DateTime and I want to get the query with latest DT_CR Date, how is it possible?
var getEmployeeNames = (from emps in reslandentity.EMPLOYEE
join timesheet in reslandentity.TIMESHEET on emps.ID equals timesheet.RES_ID
join weekcal in reslandentity.WEEK_CALENDER on timesheet.WEEK_CAL_ID equals weekcal.ID
join log in reslandentity.TIMESHEET_LOG on timesheet.ID equals log.TIMESHEET_ID
join workflow in reslandentity.TIMESHEET_WORKFLOW on log.WORKFLOW_ID equals workflow.ID
where weekcal.WEEK_START_DT.Month == month
orderby log.DT_CR select new TimesheetModel
{
EMP_ID = emps.ID,
EMPLOYEE_NAME = emps.FIRST_NAME + " " + emps.LAST_NAME,
RES_TYPE = workflow.ORG_RES_TYPE,
EMP_STATUS = workflow.ACTION,
SDate = weekcal.WEEK_START_DT,
EDate = weekcal.WEEK_END_DT,
DT_CR=log.DT_CR
}).Distinct().ToList();
model.GetTimeSheetDetails = getEmployeeNames;
Please Help me to get the Query.
You've not made it clear if you expect just a single result or a list of results (1 per timesheet).
If you just need a single result the answer by lti Tyangi will be fine.
If you need a result per timesheet you could try the following:
var getEmployeeNames = (from emps in reslandentity.EMPLOYEE
join timesheet in reslandentity.TIMESHEET on emps.ID equals timesheet.RES_ID
join weekcal in reslandentity.WEEK_CALENDER on timesheet.WEEK_CAL_ID equals weekcal.ID
join mxLog in (
from lg in reslandentity.TIMESHEET_LOG
group lg by lg.TIMESHEET_ID into lgGrp
select new {lgGrp.Key, DT_CR = lgGrp.Max(x => x.DT_CR)}
) on timesheet.ID equals mxLog.Key
join log in reslandentity.TIMESHEET_LOG on new { a = mxLog.Key, b = mxLog.DT_CR} equals new{ a = log.TIMESHEET_ID, b = log.DT_CR}
join workflow in reslandentity.TIMESHEET_WORKFLOW on log.WORKFLOW_ID equals workflow.ID
where weekcal.WEEK_START_DT.Month == month
orderby log.DT_CR select new TimesheetModel
{
EMP_ID = emps.ID,
EMPLOYEE_NAME = emps.FIRST_NAME + " " + emps.LAST_NAME,
RES_TYPE = workflow.ORG_RES_TYPE,
EMP_STATUS = workflow.ACTION,
SDate = weekcal.WEEK_START_DT,
EDate = weekcal.WEEK_END_DT,
DT_CR=log.DT_CR
}).Distinct().ToList();
model.GetTimeSheetDetails = getEmployeeNames;
here we join onto a grouping of the logs per timesheet to get the maximum date per timesheet, and then join to the logs based on both the id of the timesheet and that date
var getEmployeeNames = (from emps in reslandentity.EMPLOYEE
join timesheet in reslandentity.TIMESHEET on emps.ID equals timesheet.RES_ID
join weekcal in reslandentity.WEEK_CALENDER on timesheet.WEEK_CAL_ID equals weekcal.ID
join log in reslandentity.TIMESHEET_LOG on timesheet.ID equals log.TIMESHEET_ID
join workflow in reslandentity.TIMESHEET_WORKFLOW on log.WORKFLOW_ID equals workflow.ID
where weekcal.WEEK_START_DT.Month == month
//orderby log.DT_CR
select new TimesheetModel
{
EMP_ID = emps.ID,
EMPLOYEE_NAME = emps.FIRST_NAME + " " + emps.LAST_NAME,
RES_TYPE = workflow.ORG_RES_TYPE,
EMP_STATUS = workflow.ACTION,
SDate = weekcal.WEEK_START_DT,
EDate = weekcal.WEEK_END_DT,
DT_CR=log.DT_CR
}).OrderByDescending(x=>x.DT_CR).FirstorDefault();
OR
var getEmployeeNames = (from emps in reslandentity.EMPLOYEE
join timesheet in reslandentity.TIMESHEET on emps.ID equals timesheet.RES_ID
join weekcal in reslandentity.WEEK_CALENDER on timesheet.WEEK_CAL_ID equals weekcal.ID
join log in reslandentity.TIMESHEET_LOG on timesheet.ID equals log.TIMESHEET_ID
join workflow in reslandentity.TIMESHEET_WORKFLOW on log.WORKFLOW_ID equals workflow.ID
where weekcal.WEEK_START_DT.Month == month
//orderby log.DT_CR
select new TimesheetModel
{
EMP_ID = emps.ID,
EMPLOYEE_NAME = emps.FIRST_NAME + " " + emps.LAST_NAME,
RES_TYPE = workflow.ORG_RES_TYPE,
EMP_STATUS = workflow.ACTION,
SDate = weekcal.WEEK_START_DT,
EDate = weekcal.WEEK_END_DT,
DT_CR=log.DT_CR
}).OrderByDescending(x=>x.DT_CR).ToList().Take(1);

Categories