-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Description
ISSUE: In my ASP.NET MVC Core app with EF Core, LEFT OUTER Join with a Where rightColumnName == null
clause is always returning the one record that is the top row of the result. I'm using VS2015-Update3. And this is Code First project (not db first). Moreover, there is no FK relationship implemented between two tables.
In my following sample data tables the customer C1 has ordered Vegetables and C2 has ordered Fruits. I want to display name of potential customers C3 and C4 who have not orders yet. So, I use an Outer Join but query always returns the first cutomer C1. It seems a bug or something wrong with my where clause.
Customers Table data:
CustomerID CustName
1 C1
2 C2
3 C3
4 C4
Orders Table data:
OrderID CustomerID OrderType
1 1 V
2 2 F
3 1 V
LINQ Query to display potential customers with no orders yet:
public class TestDbController : Controller
{
public async Task<IActionResult> TestAction(List<CustomersViewModel> list)
{
var Qry = from c in Customers
join ord in Orders on c.CustomerId equals ord.CustomerId into c_o
from t in c_o.DefaultIfEmpty()
where t == null
select new CustomersViewModel() {CustName = c.CustName};
return View(qry.ToList());
}
}
SQL Server Profiler captures the following following SQL that returns all customers (instead of C3, C4 only):
exec sp_executesql N'SELECT [c].[CustNumber], @__Empty_0
FROM [Customers] AS [c]
LEFT JOIN [Orders] AS [ord] ON [c].[CustomerID] = [ord].[CustomerID]
ORDER BY [c].[CustomerID]',N'@__Empty_0 nvarchar(4000)',@__Empty_0=N''
But my view is showing only one record. Also, when I place a breakpoint at @for (int t=0; t<Model.Count; t++)
in my view shown below, it shows only 1 at the Model.Count
:
@model List<MyProject.Models.MyViewModels.CustomersViewModel>
<form asp-controller="TestDb" asp-action="TestAction" method="post">
<table class="table">
<thead>
<tr>
<th><label asp-for="@Model.First().CustName"></label></th>
</tr>
</thead>
<tbody>
@for (int t=0; t<Model.Count; t++)
{
<tr>
<td><input type="hidden" asp-for="@Model[t].CustomerId"/ </td>
<td><input type="text" asp-for="@Model[t].CustName"/></td>
</tr>
}
</tbody>
</table>
<button type="submit">Save</button>
</form>
EF version installed on the project:
I followed the instruction from this ASP.NET official article to install the EF Core. Following is the image from my Project Reference Directory: