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);
Related
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;
Here I want to join the out put of the first query(one column) to the result of the 2nd query to get a one result set. How can I merge them.(CONCAT doesn't work as required. eg: var query2 = query.concat(query1);)
var query = (from PP in _db.paymentPlans
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new {C,PP} by new {C.courseID} into totalRecievable
select new PdPpAppCourseModel
{
courseID = totalRecievable.Key.courseID,
totalAmount = totalRecievable.Sum(x => x.PP.totalAmount)
}).ToList();
var query1=(from PD in _db.paymentDetails
join PP in _db.paymentPlans on PD.paymentPlanID equals PP.paymentPlanID
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new { C,PD } by new { C.courseID, C.cricosCode, C.courseName } into paymentsCourseWise
select new PdPpAppCourseModel
{
courseID = paymentsCourseWise.Key.courseID,
cricosCode = paymentsCourseWise.Key.cricosCode,
courseName = paymentsCourseWise.Key.courseName,
paidAmount = paymentsCourseWise.Sum(x => x.PD.paidAmount)
}).ToList();
You could join query1 and query like this
var result = (from q1 in query1
join q in query on q1.courseID = q.courseID
select new PdPpAppCourseModel
{
courseID = q1.Key.courseID,
cricosCode = q1.Key.cricosCode,
courseName = q1.Key.courseName,
paidAmount = q1.Sum(x => x.PD.paidAmount),
totalAmount = q.totalAmount
}).ToList();
I have this query but I need to add a where clause that uses 'Contains()' so I can check the db for a list of accountIDs, the reason I need to do it this way is because I have to first check if there are any accountID's and if there are it must execute the 'Contains()' in the where clause but the compiler complains if I try do it this way but given what the method has to do I can't figure out another way to do it given the fact that there are so many tables joined in the query.
My code:
bool UseAcc = false;
if (accountIds != null && accountIds.Count > 0)
{
UseAcc = true;
}
var query = (from i in db.Incidents
join s in db.Sites on i.SiteID equals s.SiteID
join a in db.Accounts on i.AccountID equals a.AccountID
join st in db.Status on i.StatusID equals st.StatusID
join currentUser in db.Users on i.CurrentAssignedUser equals currentUser.UserID
join loggedByUser in db.Users on i.LoggedByUser equals loggedByUser.UserID
join createdByUser in db.Users on i.CreatedByUser equals createdByUser.UserID
join l in db.Locations on i.Location equals l.LocationID into locList
from loc in locList.DefaultIfEmpty()
join q in db.QuestionCategories on i.QuestionCategoryID equals q.QuestionCategoryID
join ia in db.IncidentActions on i.IncidentID equals ia.IncidentID into iaList
from actions in iaList.DefaultIfEmpty()
//If 'UseAcc' gets set to true then execute the contains section of the or statement
where (i.Active == true) &&
(UseAcc = false || a => accountIds.Contains(a.AccountID))
select new
{
Title = i.Title,
IncidentID = i.IncidentID,
StatusName = st.StatusName,
StatusID = i.StatusID,
ReferenceNumber = i.ReferenceNo,
AccountName = a.AccountName,
AccountID = i.AccountID,
SiteName = s.SiteName,
SiteID = i.SiteID,
LocationName = loc.LocationName,
LocationID = i.Location,
CatName = q.QuestionCategoryName,
CatID = i.QuestionCategoryID,
CurrentAssignedUser = currentUser.FirstName + " " + currentUser.LastName,
AssignedUserID = i.CurrentAssignedUser,
CreatedByUser = createdByUser.FirstName + " " + createdByUser.LastName,
DateCreated = i.LoggedDate,
DepartmentID = i.DepartmentID,
Logger = loggedByUser.FirstName + " " + loggedByUser.LastName,
LoggedBy = i.LoggedByUser,
EscalationCount = i.EscalationCount)
});
I would paste the whole method but its really big.
I have looked at examples online but they can't work either because alot of them use an AsQueryable with a single table and this query has many tables joined.
Please Help.
var accounts = db.Accounts.AsQueryable();
if (accountIds != null && accountIds.Count > 0)
{
accounts = accounts.Where(a => accountIds.Contains(a.AccountID));
}
var query = (from i in db.Incidents
join s in db.Sites on i.SiteID equals s.SiteID
join a in accounts on i.AccountID equals a.AccountID
join st in db.Status on i.StatusID equals st.StatusID
join currentUser in db.Users on i.CurrentAssignedUser equals currentUser.UserID
join loggedByUser in db.Users on i.LoggedByUser equals loggedByUser.UserID
join createdByUser in db.Users on i.CreatedByUser equals createdByUser.UserID
join l in db.Locations on i.Location equals l.LocationID into locList
from loc in locList.DefaultIfEmpty()
join q in db.QuestionCategories on i.QuestionCategoryID equals q.QuestionCategoryID
join ia in db.IncidentActions on i.IncidentID equals ia.IncidentID into iaList
from actions in iaList.DefaultIfEmpty()
select new
{
Title = i.Title,
IncidentID = i.IncidentID,
StatusName = st.StatusName,
StatusID = i.StatusID,
ReferenceNumber = i.ReferenceNo,
AccountName = a.AccountName,
AccountID = i.AccountID,
SiteName = s.SiteName,
SiteID = i.SiteID,
LocationName = loc.LocationName,
LocationID = i.Location,
CatName = q.QuestionCategoryName,
CatID = i.QuestionCategoryID,
CurrentAssignedUser = currentUser.FirstName + " " + currentUser.LastName,
AssignedUserID = i.CurrentAssignedUser,
CreatedByUser = createdByUser.FirstName + " " + createdByUser.LastName,
DateCreated = i.LoggedDate,
DepartmentID = i.DepartmentID,
Logger = loggedByUser.FirstName + " " + loggedByUser.LastName,
LoggedBy = i.LoggedByUser,
EscalationCount = i.EscalationCount)
});
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);
This is my query:
var results = from table1 in dtSplitDates.AsEnumerable()
join table2 in dtSplitDates.AsEnumerable() on (int)table1["FID"] equals (int)table2["FID"] into lj
from r in lj.DefaultIfEmpty()
select dtSplitDates2.LoadDataRow(new object[]
{
r["FID"],
r["SLNO"],
r == null ? string.Empty : r["Dates"]
}, false);
Currently i am joining on Column FID - due to which i am getting 36 records (duplicates):
However in order to avoid duplicates i need to join also on SLNO column but i am unable to write that query - please help.
As per my understanding you want two join condition; Try this
var results = from table1 in dtSplitDates.AsEnumerable()
join table2 in dtSplitDates.AsEnumerable()
on new {id1 =(int)table1["FID"], SLno1= (int)table1["SLNO"]}
equals new {id2=(int)table2["FID"], SLno2=(int)table2["SLNO"]} into lj
from r in lj.DefaultIfEmpty()
select dtSplitDates2.LoadDataRow(new object[]
{
r["FID"],
r["SLNO"],
r == null ? string.Empty : r["Dates"]
}, false);
Try to implement with this example:
For Multiple Joins:
var result=(from com in db.Company.AsEnumerable()
join c in db.Country.AsEnumerable() on com.CountryID equals c.CountryID
join s in db.State.AsEnumerable() on com.StateID equals s.StateID
join ct in db.City.AsEnumerable() on com.CityID equals ct.CityID
orderby com.Name
select new CompanyModel()
{
CompanyID = com.CompanyID,
Name = com.Name,
AddressLine1 = com.AddressLine1,
CountryID = com.CountryID,
StateID = com.StateID,
CityID = com.CityID,
Country = c.CountryID,
State = s.StateID,
City = ct.CityID,
Pin = com.Pin,
Phone = com.Phone,
}).Distinct().ToList();