user1976486 user1976486 - 2 months ago 9
C# Question

Returning cross join instead of inner join

I have two result sets from database into object and when I inner join them, it returns cross join. Following is my code:

var nw = new NorthwindEntities();
var employee1 = (from emp in nw.Employees
join ord in nw.Orders on emp.EmployeeID equals ord.EmployeeID
where emp.EmployeeID == 5
select new
{
empID = emp.EmployeeID,
empName = emp.FirstName,
ordDate = ord.OrderDate
}).ToList();

var employee2 = (from emp in nw.Employees
join ord in nw.Orders on emp.EmployeeID equals ord.EmployeeID
where emp.EmployeeID == 5
select new
{
empID = emp.EmployeeID,
empName = emp.FirstName,
shpAddress = ord.ShipAddress
}).ToList();

var employee = from e1 in employee1
join e2 in employee2 on new { e1.empID } equals new { e2.empID }
select new
{
empID = e1.empID,
empName = e1.empName,
ordDate = e1.ordDate,
orAdd = e2.shpAddress
};

gvAll.DataSource = employee.ToList();


Now when I join employee1 and employee2 into employee, I get a cross join of those data set. Any help would be highly appreciated.

My main target behind this is to have data returned from database stored in some place temporarily so I can work it with later with other data retrieved from database.

employee1 and employee2 uses same query for employee id (5) except employee1 has empID, empName and OrderDate where as employee2 has empID, empName and shipAddress. Now I want empID, empName, OrderDate and ShipAddress out of employee1 and employee2 in employee. empID is common in both but I am getting a cross join. Thank you.

Answer

In employee1 and employee2 you will aslo need the OrderId column to and then join them by both cos you need to get an equal unique key on both tables.

and from what you wrote I think that empID is not unique in either tables cos you can have more orders for same empID

So first you need a unique key on both employee1 and employee2 then you can join on that.