SQL Statement with inner join to LINQ - sql-to-linq-conversion

I need to convert my SQL statement to LINQ.
SELECT
dbo.Transactions.TypeRefID,
dbo.TransactionItems.ItemRefID,
SUM(dbo.TransactionItems.Quantity) AS Qty
FROM
dbo.TransactionItems
LEFT OUTER JOIN
dbo.Transactions ON dbo.TransactionItems.TransactionRefID = dbo.Transactions.TransactionID
GROUP BY
dbo.Transactions.TypeRefID, dbo.TransactionItems.ItemRefID
HAVING
(dbo.Transactions.TypeRefID = 1)
AND (dbo.TransactionItems.ItemRefID = 5)
I tried converting the above statement into LINQ and this is what I've done.
var query = from t in db.Transaction
join i in db.TransactionItem on t.TransactionID equals i.TransactionRefID
where t.TypeRefID == 1 && i.ItemRefID == 5
group i by new
{
t.TypeRefID,
i.ItemRefID
} into g
select new
{
TypeRefID = g.Key.TypeRefID,
ItemRefID = g.Key.ItemRefID,
Quantity = g.Sum(q => q.Quantity)
};
When I run my code I get error "System.Linq.Queryable.FirstOrDefault(...) returned null"
I'm using it like this
if (query != null)
string qty = query.FirstOrDefault().Quantity.ToString();
The error is called on "query.FirstOrDefault().Quantity.ToString()"
How to avoid this error?

Related

How to write join query with multiple column - LINQ

I have a situation where two tables should be joined with multiple columns with or condition. Here, I have a sample of sql query but i was not able to convert it into linq query.
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
This is how i have write linq query
await (from cm in Context.CustomerMaster
join li in list.PortalCustomerDetailViewModel
on new { OldNLKNo = cm.OldAcNo, NewNLKNo = cm.CustomerCode } equals new { OldNLKNo = li.OldNLKNo, NewNLKNo = li.NewNLKNo }
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
But this query doesn't returns as expected. How do I convert this sql query into linq.
Thank you
You didn't tell if list.PortalCustomerDetailViewModel is some information in the database, or in your local process. It seems that this is in your local process, your query will have to transfer it to the database (maybe that is why it is Tmp in your SQL?)
Requirement: give me all properties of a CustomerMaster for all CustomerMasters where exists at least one PortalCustomerDetailViewModel where
customerMaster.CustomerCode == portalCustomerDetailViewModel.NewNLKNo
|| customerMaster.OldAcNo == portalCustomerDetailViewModel.OldNLKNo
You can't use a normal Join, because a Join works with an AND, you want to work with OR
What you could do, is Select all CustomerMasters where there is any PortalCustomerDetailViewModel that fulfills the provided OR:
I only transfer those properties of list.PortalCustomerDetailViewModel to the database that I need to use in the OR expression:
var checkProperties = list.PortalCustomerDetailViewModel
.Select(portalCustomerDetail => new
{
NewNlkNo = portalCustomerDetail.NewNlkNo,
OldNLKNo = portalCustomerDetail.OldNLKNo,
});
var result = dbContext.CustomerMasters.Where(customerMaster =>
checkProperties.Where(checkProperty =>
customerMaster.CustomerCode == checkProperty.NewNLKNo
|| customerMaster.OldAcNo == checkProperty.OldNLKNo)).Any()))
.Select(customerMaster => new CustomerInfoViewModel
{
Id = customerMaster.Id,
Name = customerMaster.Name,
...
});
In words: from each portalCustomerDetail in list.PortalCustomerDetailViewModel, extract the properties NewNKLNo and OldNLKNo.
Then from the table of CustomerMasters, keep only those customerMasters that have at least one portalCustomerDetail with the properties as described in the OR statement.
From every remaining CustomerMasters, create one new CustomerInfoViewModel containing properties ...
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
You don't have to use the join syntax. Adding the predicates in a where clause could get the same result. Try to use the following code:
await (from cm in Context.CustomerMaster
from li in list.PortalCustomerDetailViewModel
where cm.CustomerCode == li.NewNLKNo || cm.OldAcNo = li.OldNLKNo
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
var result=_db.Customer
.groupjoin(_db.#temp ,jc=>jc.CustomerCode,c=> c.NewNLKNo,(jc,c)=>{jc,c=c.firstordefault()})
.groupjoin(_db.#temp ,jc2=>jc2.OldAcNo,c2=> c2.OldNLKNo,(jc2,c2)=>{jc2,c2=c2.firstordefault()})
.select(x=> new{
//as you want
}).distinct().tolist();

I need to transform a SQL query with inner joins to Linq in Entity Framework

I am very new to translating queries to entity, I don't know how to replace that query into linq in my code
select
brules.rule_description, brules.user_story_number,
so.source_name,
count(dlog.row_id) as error_count,
cast(execution_date as date) as execution_date
from
br.lk_business_rules brules
inner join
br.business_rules_detailed_log dlog on dlog.user_story_number = brules.user_story_number
inner join
br.lk_business_rules_source so on so.source_id = source_id_fk
where
brules.status_id_fk = 3
group by
brules.rule_description, brules.user_story_number,
so.source_name, cast(execution_date as date)
order by
brules.rule_description
i tried this:
var query = from br in _context.Lk_business_rules
join detLog in _context.Business_rules_detailed_log
on br.User_story_number equals detLog.User_story_number
join source in _context.Lk_business_rules_source
on detLog.Source_id equals source.Source_id
where br.Status_id_fk == 3
select new
{
Business_rule_description = br.Rule_description,
Business_rule_storynumber = br.User_story_number,
Source = source.Source_name,
Error_count = detLog.Row_id.Count,
Date = detLog.Execution_date
};
but not succed

Change to linq left join query

SELECT I.*, SI.SupplierID FROM item I
LEFT JOIN SupplierItem SI ON I.ItemID = SI.ItemID AND I.Price = SI.Price
WHERE I.CurrentQty <= I.ReorderLevel and SI.SupplierID = 'AlPA'
how can i change that sql query to Linq Query.
The below query will convert your Sql query to Linq query
var data =
from row in db.item
join row1 in db.SupplierItem
on new { ID= row.ItemID , Price = row.Price }
equals new { ID= row1.ItemID , Price = row1.Price } into joinedData
from row2 in joinedData.DefaultIfEmpty()
where row.CurrentQty <= row.ReorderLevel && row2.SupplierID == "AlPA"
select new {
item = row,
SupplierID = row2.SupplierID
};

Sql query to linq convert

Can anyone help me to translate my sql query to linq? I am not so good in linq can anyone help me out with it please .
select
s.UploadFilename ,
a.ID,
isnull(s.Status_id,1) as 'Status_id' ,
a.CaseID,
a.RecordType,
a.ColumnName,
a.FieldName,
a.OldValue,
a.NewValue,
a.ModifiedBy,
A.ModifiedOn,
isnull(u.UserName,'') as 'UserName'
from [dbo].[AuditTrail] as A
left join Case_Status as s
on s.Case_Id=A.CaseID
left join [dbo].[User] as u
on a.ModifiedOn =u.UserID
where A.CaseID=5338
This is not the answer, my query is big, it was not accepting this query as comment.
This query is not returning records :
var AuditTrailFile = (from AT in db.AuditTrails
join ATCS in db.AssnAuditTrailCaseStatus
on new {ID = AT.ID} equals new { ID = (int)(ATCS.AuditTrialID) }
into ATCS_join
from ATCS in ATCS_join.DefaultIfEmpty()
join CS in db.Case_Status on new { Case_StatusId = (int)(ATCS.CaseStatusID) }
equals new { Case_StatusId = CS.Case_StatusId } into CS_join
from CS in CS_join.DefaultIfEmpty()
where
AT.CaseID == CaseID
orderby
AT.ModifiedOn descending
select new
{
ID = (int?)AT.ID,
Case_StatusId = CS.Case_StatusId != null ? CS.Case_StatusId : 1, //Case_StatusId comes for row whose FieldName=Status Else No Case_StatusId
AT.CaseID,
AT.RecordType,
AT.ColumnName,
AT.FieldName,
AT.OldValue,
AT.NewValue,
AT.ModifiedBy,
UserName = AT.User != null ? AT.User.UserName : "",
AT.ModifiedOn,
UploadFilename = CS.UploadFilename
}).ToList();

LINQ doesn't work with a "select isnull" query..? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Equivalent of SQL ISNULL in LINQ?
Using IsNull or select COALESCE in Linq..?
I've tried this query in LINQ:
string query = #"SELECT ISNULL(P.firstname, s.firstname) AS Expr1,ISNULL(P.lastname,
s.lastname) AS Expr2 FROM comment AS C LEFT OUTER JOIN professor AS P ON P.ID =
C.PID LEFT OUTER JOIN student AS s ON s.ID = C.SID
WHERE (C.VID = 2)";
ArrayList allNames=null;
using (var context = new NewsReaderEntities())
{
ObjectQuery<string> results = context.CreateQuery<string>(query);
// ObjectQuery<string> results1 = context.CreateQuery<string>
(query1,parameters);
foreach (string result in results )
{
allNames.Add(result);
}
}
return allNames;
}
but it returns the error:
linq 'ISNULL' cannot be resolved into a valid type or function. Near
simple identifier,
I've also tried this query:
SELECT COALESCE(p.firstname, s.firstname), COALESCE(p.lastname, s.lastname)
FROM comment c
LEFT JOIN Professor p
ON c.pid = p.id
LEFT JOIN Student s
ON c.sid = s.id
WHERE c.vid = 2
This also raises an error.
Both work okay in SQL Management. Any ideas?
See this example:
var query = from p in Pets select p;
if (OwnerID != null) query = query.Where(x => x.OwnerID == OwnerID);
if (AnotherID != null) query = query.Where(x => x.AnotherID == AnotherID);
if (TypeID != null) query = query.Where(x => x.TypeID == TypeID);
Hope this help you