I have a Linq query to fetch data from databse using entity framework. I have to apply the given sql condetion to the linq query.My sample sql query is
DECLARE #EmrId NVARCHAR(50)
set #EmrId='784197621725304'
SELECT
[ftp_imptlg_ImprtTyp_id],[ftp_imptlg_daypath],[ftp_imptlg_subfolderpath]
,[ftp_imptlg_emirates_id],[ftp_imptlg_srcfile_name],[ftp_imptlg_filereadon]
,[ftp_imptlg_opr_status],[ftp_imptlg_doc_no],[ftp_imptlg_emp_id]
,[ftp_imptlg_upld_filename] ,[ftp_imptlg_doctype_id]
FROM [C3KYC].[dbo].[ftp_import_logs] AS c
inner join tm_doc_type as d on c.[ftp_imptlg_doctype_id]=d.doc_typeid
inner join tm_import_type as e on c.[ftp_imptlg_ImprtTyp_id]=e.imprttype_id
WHERE c.ftp_imptlg_emirates_id = case when #EmrId ='0' then
c.ftp_imptlg_emirates_id else #EmrId end
AND
c.ftp_imptlg_opr_status='failed'
and d.doc_typeid=6
and e.imprttype_id='2'
I tried the below linq query
string strEmrid = EmiratesId != null ? EmiratesId : "0";
using (var db = new DB_KYC3Entities())
{
db.Configuration.ProxyCreationEnabled = false;
List<ImportLogDetails> listofLogDetails = (from c in db.ftp_import_logs
join d in db.tm_doc_type on c.ftp_imptlg_doctype_id equals d.doc_typeid
join e in db.tm_import_type on c.ftp_imptlg_ImprtTyp_id equals e.imprttype_id
where c.ftp_imptlg_ImprtTyp_id == ImportTypeId
&& c.ftp_imptlg_emirates_id == strEmrid
&& c.ftp_imptlg_opr_status== "Failed"
&& d.doc_typeid== 6
&& e.imprttype_id== "2"
select new ImportLogDetails
{
ImportType = e.imprtTye_name,
SourcePath = c.ftp_imptlg_subfolderpath,
DateOfAction = c.ftp_imptlg_filereadon,
DocumentType = d.doctype_name,
EmiratesId = c.ftp_imptlg_emirates_id,
Status = c.ftp_imptlg_opr_status,
KycEmployeeId = c.ftp_imptlg_emp_id,
DocumentTypeId = c.ftp_imptlg_doctype_id
}).ToList();
return listofLogDetails;
You can use ?: operator in LINQ,
x.Where( x => x.ftp_imptlg_emirates_id == (
x.ftp_imptlg_emirates_id == "0" ? "0" : x.ftp_imptlg_emirates_id
))
Your query,
string strEmrid = EmiratesId != null ? EmiratesId : "0";
using (var db = new DB_KYC3Entities())
{
db.Configuration.ProxyCreationEnabled = false;
List<ImportLogDetails> listofLogDetails = (from c in db.ftp_import_logs
join d in db.tm_doc_type on c.ftp_imptlg_doctype_id equals d.doc_typeid
join e in db.tm_import_type on c.ftp_imptlg_ImprtTyp_id equals e.imprttype_id
where c.ftp_imptlg_ImprtTyp_id == ImportTypeId
&&
c.ftp_imptlg_emirates_id == (strEmirId == "0" ? c.ftp_imptlg_emirates_id : strEmirid)
&& c.ftp_imptlg_opr_status== "Failed"
&& d.doc_typeid== 6
&& e.imprttype_id== "2"
select new ImportLogDetails
{
ImportType = e.imprtTye_name,
SourcePath = c.ftp_imptlg_subfolderpath,
DateOfAction = c.ftp_imptlg_filereadon,
DocumentType = d.doctype_name,
EmiratesId = c.ftp_imptlg_emirates_id,
Status = c.ftp_imptlg_opr_status,
KycEmployeeId = c.ftp_imptlg_emp_id,
DocumentTypeId = c.ftp_imptlg_doctype_id
}).ToList();
return listofLogDetails;
Related
following query is throwing error "The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin"
from ph in context.PrPayfileHeaders
join pp in context.PrPayfileParticipants on ph.PayfileHeaderId equals pp.PayfileHeaderId
join sec in context.SecUsers on pp.AnalystUserId equals sec.UserId
join hp in context.HcmPerson on // Error statement
new
{
key1 = pp.ParticipantEmpNumber,
key2 = ph.PayPeriod
}
equals
new
{
key1 = hp.EmployeeNumber,
key2 = hp.PeriodId
}
into fg
from fgi in fg.DefaultIfEmpty()
where ph.PayfileType == payFileType && ph.IntfControlId == intf_Control_Id && (region == null || ph.RegionName == region)
select new FinalPayFileInfo
{
Participant_id = pp.PayfileParticipantId,
Home_country = fgi.HomeCountry,
Region_name = ph.RegionName,
Analyst_name = sec.FirstName + " " + sec.LastName,
Full_name = fgi.FullName,
Department = pp.DeptNumber,
Cost_center = pp.CostCenter,
Local_currency = pp.LocalCurrency,
Comm_attribute1 = pp.CommAttribute1,
Comm_attribute2 = pp.CommAttribute2,
Comm_attribute3 = pp.CommAttribute3,
Comm_attribute4 = pp.CommAttribute4,
Comm_attribute5 = pp.CommAttribute5,
Comm_attribute6 = pp.CommAttribute6,
Comm_attribute7 = pp.CommAttribute7
};
I am working on asp.net core application. I have following linq query which is being used to fill a model. This model has a property qtryregions which is a list. How can I fill it in one query.
public JsonResult PODetailsList(int id)
{
List<PODetailsFull> Products;
Products =
(from d in db.PODetails
join p in db.Products on d.ProductID equals p.ProductID
where d.POID == id
select new PODetailsFull
{
PODetailID = d.PODetailID,
//QtyRegion = new List<string>() { Region.Region + " " + POAllocation.Allocate != null ? POAllocation.Allocate.ToString() : "" },
Sku = p.Sku,
Cntnr20 = p.Cntnr20 ?? 0,
Cntnr40 = p.Cntnr40 ?? 0,
Cntnr40HQ = p.Cntnr40HQ ?? 0,
}).ToList();
foreach (var product in Products)
{
var result = (from POAllocation in db.POAllocations.Where(p => p.PODetailID == product.PODetailID)
join regions in db.Regions on POAllocation.RegionID equals regions.RegionID
select regions.Region + " " + POAllocation.Allocate ?? ""
).ToList();
product.QtyRegion = result;
}
return Json(new { data = Products }, JsonRequestBehavior.AllowGet);
}
I don't want to use above foreach and want to populate product.Qtyregion in first linq query.
Please suggest.
Is this what you want?
Products = (
from d in db.PODetails
join p in db.Products on d.ProductID equals p.ProductID
where d.POID == id
select new PODetailsFull
{
PODetailID = d.PODetailID,
//QtyRegion = new List<string>() { Region.Region + " " + POAllocation.Allocate != null ? POAllocation.Allocate.ToString() : "" },
Sku = p.Sku,
Cntnr20 = p.Cntnr20 ?? 0,
Cntnr40 = p.Cntnr40 ?? 0,
Cntnr40HQ = p.Cntnr40HQ ?? 0,
QtyRegion = (
from POAllocation in db.POAllocations.Where(p => p.PODetailID == d.PODetailID)
join regions in db.Regions on POAllocation.RegionID equals regions.RegionID
select regions.Region + " " + POAllocation.Allocate ?? "").ToList(),
}).ToList();
Try to use Group By to avoid N+1 queries issue:
Products = (
from d in db.PODetails
join p in db.Products on d.ProductID equals p.ProductID
join palloc in db.POAllocations on d.PODetailID equals palloc.PODetailID
group by new {
PODetailID = d.PODetailID,
Sku = p.Sku,
Cntnr20 = p.Cntnr20,
Cntnr40 = p.Cntnr40,
Cntnr40HQ = p.Cntnr40HQ }
into grp
where grp.Key.POID == id
select new PODetailsFull
{
PODetailID = grp.Key.PODetailID,
QtyRegion = grp,
Sku = grp.Key.Sku,
Cntnr20 = grp.Key.Cntnr20 ?? 0,
Cntnr40 = grp.Key.Cntnr40 ?? 0,
Cntnr40HQ = grp.Key.Cntnr40HQ ?? 0
}).ToList();
Doing some stuff linq left join query but facing some problem. Not able to get proper result following sql query need to convert into linq
INSERT INTO tbl_service_order_attributes_versioning(ServiceOrderNo, AttributeId, AttributeValue, parentid, AttributeType, Dt_Stamp, VERSION)
SELECT
T.ServiceOrderNo, T.COIID, T.COI_Identifier,
#pid, 'MBM', getDate(), #ORDERVERSION
FROM
#temp1 T
LEFT JOIN
tbl_service_order_attributes_versioning O WITH(NOLOCK)
ON T.ServiceOrderNo = O.ServiceOrderNo COLLATE database_default
AND T.COIID = O.AttributeID
AND O.PARENTID = #pid
WHERE
O.ServiceOrderNo IS NULL
I have converted this query into a Linq query:
var soiAttr = (from s in ctxParser.TBL_SERVICE_ORDER_ATTRIBUTES_VERSIONING
where s.ParentId == parentId
select s).ToList();
var resultJoinCOI = (from soaI in soiAttr
join iFoi in listFOI on soaI.ServiceOrderNo equals iFoi.fulfilmentOrderItemIdentifier
where iFoi.coiId == soaI.AttributeId &&
iFoi.parentId == parentId &&
soaI.ServiceOrderNo == null
select iFoi).ToList();
if (resultJoinCOI.Count > 0)
{
var listToInsert = (from item in resultJoinCOI
select new TBL_SERVICE_ORDER_ATTRIBUTES_VERSIONING
{
ServiceOrderNo = item.fulfilmentOrderItemIdentifier,
AttributeId = item.coiId,
AttributeValue = item.coiIdentifier,
ParentId = parentId,
AttributeType = "MBM",
DT_Stamp = DateTime.Now,
VERSION = orderVersion
});
ctxParser.TBL_SERVICE_ORDER_ATTRIBUTES_VERSIONING.AddRange(listToInsert);
ctxParser.SaveChanges();
}
The code is executed but result are not correct.
You need to use DefaultIfEmpty (https://msdn.microsoft.com/en-us/library/bb360179.aspx). Here's a reading from MSDN: https://msdn.microsoft.com/en-us/library/bb397895.aspx
In your case it would be something like:
var resultJoinCOI = (
from iFoi in listFOI
join soaI in soiAttr on iFoi.fulfilmentOrderItemIdentifier equals soaI.ServiceOrderNo into res
from subIFoi in res.DefaultIfEmpty()
where iFoi.coiId == soaI.AttributeId && iFoi.parentId == parentId && subIFoi == null
select iFoi).ToList();
Following code that execute successfully. and getting right result.
var soiAttr = (from s in ctxParser.TBL_SERVICE_ORDER_ATTRIBUTES_VERSIONING
where s.ParentId == parentId
select s).ToList();
var resultJoinCOI = (from iFoi in listFOI
join soaI in soiAttr on
new
{
ServiceOrderNo = iFoi.fulfilmentOrderItemIdentifier,
AttributeId = iFoi.coiId
}
equals new
{
ServiceOrderNo = soaI.ServiceOrderNo,
AttributeId = soaI.AttributeId
}
into res
from subFoi in res.DefaultIfEmpty()
select new
{
fulfilmentOrderItemIdentifier = iFoi.fulfilmentOrderItemIdentifier,
coiId = iFoi.coiId,
coiIdentifier = iFoi.coiIdentifier,
AttributeId = subFoi == null ? 0 : subFoi.AttributeId,
ParentId = subFoi == null ? parentId : subFoi.ParentId,
ServiceOrderNo = subFoi == null ? string.Empty: subFoi.ServiceOrderNo
});
if (resultJoinCOI != null)
{
if (resultJoinCOI.Count() > 0)
{
var listToInsert = (from item in resultJoinCOI
select new TBL_SERVICE_ORDER_ATTRIBUTES_VERSIONING
{
ServiceOrderNo = item.fulfilmentOrderItemIdentifier,
AttributeId = item.coiId,
AttributeValue = item.coiIdentifier,
ParentId = parentId,
AttributeType = "MBM",
DT_Stamp = DateTime.Now,
VERSION = orderVersion
});
ctxParser.TBL_SERVICE_ORDER_ATTRIBUTES_VERSIONING.AddRange(listToInsert);
ctxParser.SaveChanges();
}
}
In this way we can implement left join in linq. as per above SQL Query(see above sql statement).
My query looks like this:
var rport = from exc in db.Exception_Datas
join emp in db.Emp_infos on exc.Emp_id equals emp.ID
where (exc.Action_date >= frm && exc.Action_date <= to) &&
emp.Branch == cmbBranch.SelectedValue &&
emp.Dept == cmbDept.SelectedValue &&
emp.ID == Convert.ToInt32(cmbEmp.SelectedValue)
select new
{
emp.Emp_name,
emp.ID,
emp.Designation,
emp.Dept,
emp.Branch,
exc.Action_date
};
I am contracting cmbEmp.Items like this:
var allEmp = from emp in db.Emp_infos select emp;
myItem.Text = "--Select--";
myItem.Value = "0";
cmbEmp.Items.Add(myItem);
foreach (var semp in allEmp)
{
myItem = new RadComboBoxItem();
myItem.Text = semp.Emp_name.ToString();
myItem.Value = semp.ID.ToString();
cmbEmp.Items.Add(myItem);
}
I've followed some other question and post in SO and out of SO. But any of them didn't helped me solve the problem. I am getting this error:
{"Input string was not in a correct format."} System.SystemException {System.FormatException}
Issue seems to be on this line. Convert.ToInt32(cmbEmp.SelectedValue). Make sure it parsed correctly and parsed it before using in linq query. Try like this
int empId;
if (Int32.TryParse(cmbEmp.SelectedValue, out empId))
{
var rport = from exc in db.Exception_Datas
join emp in db.Emp_infos on exc.Emp_id equals emp.ID
where (exc.Action_date >= frm && exc.Action_date <= to) &&
emp.Branch == cmbBranch.SelectedValue &&
emp.Dept == cmbDept.SelectedValue &&
emp.ID == empId
select new
{
emp.Emp_name,
emp.ID,
emp.Designation,
emp.Dept,
emp.Branch,
exc.Action_date
};
}
After getting my join to work I seem to have gotten stuck on the count bit.
What I am attempting below is get a count of documents printed based on the join below.
What would the code be to get the count per 'guardiandocsrequired'?
var guardianEntityType = new {EntityTypeFK = "GUARDIAN"};
return (from d in dbContext.GuardianDocsRequireds
join p in dbContext.DocumentPrintingLogs on
new { docTypeFK = d.DocTypeFK, entityFK = d.GuardianFK } equals
new { docTypeFK = p.DocTypeFK, entityFK = p.EntityFK }
where d.GuardianFK == entityPK && p.ItemGroupFK == itemGroupID && p.EntityTypeFK == "GUARDIAN"
group d by new
{
d.GuardianFK,
d.DocTypeFK,
d.DocumentType.DocTypeDescription,
d.RequiredStatus
}
into res
select new DocumentsRequired
{
EntityPK = res.Key.GuardianFK,
EntityType = entityType,
DocTypeFK = res.Key.DocTypeFK,
DocTypeDescription = res.Key.DocTypeDescription,
RequiredStatus = res.Key.RequiredStatus,
PrintCount = ???
}
).ToList();
If it helps, I have written the sql to produce exactly what I require as follows:
SELECT gdr.DocRequiredID,gdr.RequiredDate,gdr.GuardianFK,gdr.DocTypeFK,gdr.RequiredStatus,
COUNT(dpl.DocPrintedID) AS documentsPrinted
FROM dbo.GuardianDocsRequired gdr
LEFT OUTER JOIN dbo.DocumentPrintingLog dpl ON gdr.DocTypeFK = dpl.DocTypeFK
AND gdr.GuardianFK = dpl.EntityFK
AND dpl.EntityTypeFK = 'GUARDIAN'
WHERE gdr.GuardianFK = #entityPK
GROUP BY gdr.DocRequiredID,gdr.RequiredDate,gdr.GuardianFK,gdr.DocTypeFK,gdr.RequiredStatus
Do you mean sth like this?
var guardiandocsrequired = (from d in dbContext.GuardianDocsRequireds
join p in dbContext.DocumentPrintingLogs on
new { docTypeFK = d.DocTypeFK, entityFK = d.GuardianFK } equals
new { docTypeFK = p.DocTypeFK, entityFK = p.EntityFK }
where d.GuardianFK == entityPK && p.ItemGroupFK == itemGroupID && p.EntityTypeFK == "GUARDIAN"
group d by new
{
d.GuardianFK,
d.DocTypeFK,
d.DocumentType.DocTypeDescription,
d.RequiredStatus
}
into res
select new DocumentsRequired
{
EntityPK = res.Key.GuardianFK,
EntityType = entityType,
DocTypeFK = res.Key.DocTypeFK,
DocTypeDescription = res.Key.DocTypeDescription,
RequiredStatus = res.Key.RequiredStatus,
PrintCount = ???
}
).ToList();
int cnt = guardiandocsrequired.Count;
return guardiandocsrequired;