Join between 3 table - c#

I have 3 table User,HumanCustomer,CompanyCustomer
I want to join between tables with LINQ but my query is not working and its returning null
Query:
var query = (from users in _ctx.Users
join hCustomer in _ctx.HumanCustomers on users.Id equals hCustomer.UserId
join cCustomer in _ctx.CompanyCustomers on users.Id equals cCustomer.UserId
select new
{
users.Id,
users.Mobile,
hCustomer.LastName,
hCustomer.Name,
cCustomer.CompanyName
});
foreach (var item in query)
{
AllCustomerViewModel allCustomer = new AllCustomerViewModel();
if (item.Name != null)
{
allCustomer.UserId = item.Id;
allCustomer.FullName = item.Name + item.LastName;
allCustomer.Mobile = item.Mobile;
Customer.Add(allCustomer);
}
}
The code does not enter foreach
I think the problem is using UserId twice because when I delete
join cCustomer in _ctx.CompanyCustomers on users.Id equals cCustomer.UserId
the query runs correctly.

Perhaps your issue is the dynamic variable you are attempting to iterate over.
You could try:
foreach (dynamic item in query)
Alternatively, you write the class to hold the values you are selecting out by updating the beginning of your query to:
var query = (from users in _ctx.Users
join hCustomer in _ctx.HumanCustomers on users.Id equals hCustomer.UserId
join cCustomer in _ctx.CompanyCustomers on users.Id equals cCustomer.UserId
select new MyClass
{
Id = users.Id,
Mobile = users.Mobile,
LastName = hCustomer.LastName,
Name = hCustomer.Name,
CompanyName = cCustomer.CompanyName
});

you can try this way..
var query = (from users in _ctx.Users
join hCustomer in _ctx.HumanCustomers on users.Id equals hCustomer.UserId
join cCustomer in _ctx.CompanyCustomers on users.Id equals cCustomer.UserId
select new
{
Id = users.Id,
Mobile = users.Mobile,
LastName = hCustomer.LastName,
Name = hCustomer.Name,
CompanyName = (cCustomer == null ? "" : cCustomer .CompanyName)
});

Related

In c#, how do you convert CAST CASE WHEN and SUM from sql to linq?

Good day, everyone!
I'm working on a c# test automation script, and I have a sql query that returns a few values based on a few checks with cast, Case When, and Sum - but now we need to transfer it to Entity Framework as a linq query, and I'm not sure how to do so.
Could someone please assist me with this?
Here is my sql query
SELECT
co.orderId AS OrderId
,(SELECT
COUNT(*)
FROM ci_orders (NOLOCK) co
INNER JOIN Customer (NOLOCK) cust
ON cust.IdCustomer = co.customerId
WHERE cust.Email = c.Email
AND co.PaymentTransactionStatusID = 1)
AS CustomerOrdersCount
,co.PitStopStatus AS PitStopStatus
,(SELECT
SUM(ops.Price + ops.QuantityDiscount)
FROM OrderProductSelect (NOLOCK) ops
WHERE ops.OrderId = 2257327)
AS NetPrice
,CAST(CASE WHEN Exists (SELECT
oi.Id
FROM OrderIssues (NOLOCK) oi
LEFT JOIN PitStops ps
ON ps.Id = oi.PitStopId
WHERE oi.OrderId = co.orderId
AND IssueType = 'HighValueOrder') THEN 1
ELSE 0 END AS BIT)
AS IsHighValuePitStop
FROM ci_orders (NOLOCK) co
INNER JOIN Customer (NOLOCK) c
ON c.IdCustomer = co.customerId
WHERE co.orderId =2257327
#eldar - I tried below way
using (var context = GetDbContext())
{
var yellowOrder = context.YellowOrders.FirstOrDefault(x => x.OrderId == orderId);
var result = (from co in context.Orders
join c in context.Customers
on co.customerId equals c.IdCustomer
where co.orderId == orderId
select new
{
OrderId = orderId,
IsHighValuePitStop = (from oi in context.OrderIssues
join ps in context.PitStops
on oi.PitStopId equals ps.Id
where oi.OrderId == orderId && ps.IssueType == "HighValueOrder")
}).Any();
return yellowOrder != null;
}
You can achieve Case When in linq with a ternary (?:) operator. And since your queries are mostly inner selects your linq should look like this :
var result = await (
from co in context.ci_orders
join c in context.Customers on co.customerId eqals c.IdCustomer
where co.orderId =2257327
select new { // here your inner selects go
OrderId = co.orderId,
IsHighValuePitStop = (from oi in context.OrderIssues
join ps in context.PitStops on oi.PitStopId equals ps.Id
where oi.OrderId = co.orderId and oi.IssueType = 'HighValueOrder').Any(), // you could use ternary operator but Any already returns a boolean value ? true : false would be meaningless
NetPrice = context.OrderProductSelect.Where(r=> r.OrderId = 2257327).Sum(ops=> ops.Price + ops.QuantityDiscount),
co.PitStopStatus,
CustomerOrdersCount = (from co in context.ci_orders
join cust context.Customer on co.customerId equals cust.IdCustomer
where cust.Email = c.Email
&& co.PaymentTransactionStatusID = 1
select co).Count()
}).ToArrayAsync()

c# SQL Query error when trying to join a table

I am having diffculties joining a table in my code. Below you can see my code, I am getting an error on the join 2 table trying to connect my parts table.
if (query.Any()) // Check if REG is in the Database
{
int carID = query.FirstOrDefault().Id;
string carRegg = query.FirstOrDefault().regNo;
string carMake = query.FirstOrDefault().Make;
string carModel = query.FirstOrDefault().Model;
var test = (from a in dbC.Cars
where a.Id == carID
join b in dbC.Services on a.Id equals b.ServiceWrkNo
join c in dbC.PartsUseds on b.ServiceWrkNo equals c.PartsUsedNo
join d in dbC.Parts on c.PartsUsedNo equals d.PartName
select new
{
serviceNum = b.ServiceWrkNo,
PartNo = c.PartsUsedNo,
replacedParts = d.PartName
}).ToList();
the database I created from a model first method is below.
Your join do seems a little bit off -- could you try the join with the following columns
var test = (from a in dbC.Cars
where a.Id == carID
join b in dbC.Services on a.Id equals b.CarId
join c in dbC.PartsUseds on b.ServiceWrkNo equals c.ServiceServiceWrkNo
join d in dbC.Parts on c.PartsPartNo equals d.PartNo
select new
{
serviceNum = b.ServiceWrkNo,
PartNo = c.PartsUsedNo,
replacedParts = d.PartName
}).ToList();

Linq query is getting more records than sql query

I have a sql query which will give me around 30 record but the same query once I changed to linq query its giving me thousands of record. I cant find the actual root cause of the problem can any one help me ...
sql query
select
DLId = p.Id,
TopicId = st.Id,
TopicName = at.Name,
PrimaryOrg = bo.BusinessUnit,
StatusId = ns.ID,
ModifiedBy = pa.LastName
from STopics st
join ATopics at on st.Id = at.Id
join Students p on st.StudentId = p.Id
join Sorgs sbu on at.BUorgID = sbu.BUOrgID
join BOrgs bo on sbu.BUOrgID = bo.ID
join Status ns on st.SID = ns.ID
join Students pa on st.NominatedBy = pa.Email
where p.IsActive = 1 and sbu.StudentID = 123 and sbu.IsActive = 1
and the linq query is
(from st in Context.STopics
join at in Context.ATopics on st.Id equals at.Id
join p in Context.Students on st.StudentId equals p.Id
join sbu in Context.Sorgs on at.BUorgID equals sbu.BUOrgID
join bo in Context.BOrgs on sbu.BUOrgID equals bo.ID
join ns in Context.Status on st.SID equals ns.ID
join pa in Context.Students on st.NominatedBy equals pa.Email
where p.IsActive==true && sbu.StudentID == 123 && sbu.IsActive == true
select new result()
{
DLId = p.Id,
TopicId = st.Id,
TopicName = at.Name,
PrimaryOrg = bo.BusinessUnit,
StatusId = ns.ID,
ModifiedBy = pa.LastName
})
(from st in Context.STopics
join at in Context.ATopics on st.Id equals at.Id
join p in Context.Students on new { st.StudentId, p.IsActive } equals new { p.Id , true}
join sbu in Context.Sorgs on new { sbu.BUorgID, sbu.IsActive,sbu.StudentID } equals new { at.BUorgID , true, 123}
join bo in Context.BOrgs on sbu.BUOrgID equals bo.ID
join ns in Context.Status on st.SID equals ns.ID
join pa in Context.Students on st.NominatedBy equals pa.Email
select new result()
{
DLId = p.Id,
TopicId = st.Id,
TopicName = at.Name,
PrimaryOrg = bo.BusinessUnit,
StatusId = ns.ID,
ModifiedBy = pa.LastName
})
Can you try this one, if you want to get exact issue, you can get how sql query is generated from the linq statements, linq query uses lots of inner query methodology
var query= your linqquery;
string sqlQuery=query.ToString();
you can review sqlQuery.

Query entity select, inner join and count

i want to translate this SQL query :
SELECT FirstName,LastName, WaiterId, Count(*) AS compte
FROM Waiter
INNER JOIN Client on Waiter.Id = Client.WaiterId
GROUP BY WaiterId,lastname, firstname
ORDER BY compte DESC;
in entity framework.
I tried something like this :
var query = (from w in db.Waiter
join c in db.Client on w.Id equals c.WaiterId
group c by c.WaiterId into g
//orderby
select new
{
WaiterId = g.Key,
count = g.Count()
});
but my select don't work. I can't select FirstName and LastName and i don't even know if my count is good.
You need to include all the properties in the group by.
var query = (from w in db.Waiter
join c in db.Client on w.Id equals c.WaiterId
group c by new { c.FirstName, c.LastName, c.WaiterId} into g
orderby g.Count() descending
select new
{
FirstName = g.Key.FirstName,
LastName = g.Key.LastName,
WaiterId = g.Key.WaiterId,
count = g.Count()
});

How do I change this query to linq to sql?

Query:
select emp.empname as Name, dep.depname as Department
from Employee as emp
inner join Department as dep on emp.depid=dep.depid
where emp.id='2'
How can I change this to linq to sql?
var id = 2;
var qry = from e in db.Employees
where e.Id == id
select new {
Name = e.EmpName,
Department = e.Department.DepName
};
(assumes the parent-association between employee and department is defined in the DBML)
and if you expect exactly one such:
var record = qry.Single();
Console.WriteLine(record.Name);
Console.WriteLine(record.Department);
Approximately:
from e in dc.Employee
join d in dc.Department on e.depid equals d.depid
where e.id == '2'
select new
{
Name = e.empname,
Department = d.depname
}
This is why LINQ is so great: there is no reason to even join with the Departments table to get it to work:
from employee in db.Employees
where employee.id == 2
select new
{
Name = employee.empname,
Department = employee.Department.depname
};

Categories

Resources