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, something wrong with my where clause.
Customers table :
CustomerID CustName
1 C1
2 C2
3 C3
4 C4
Orders table :
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.Name};
return View(qry.ToList());
}
}
UPDATE :
According to @IvanStoev, this seems to be an EF core bug. I should have pointed out that I'm using the following technologies: ASP.NET CORE, EF Core, Visual Studio 2015 - UPDATE 3, and SQL Server Express 2014. I'm including a tag for EF Core in the post.
If someone can find a solution or a workaround, please let me know.
UPDATE 2 :
SQL Server Profiler captures the following following SQL:
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>
This is actually your query and works (against say Northwind):
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 c;
But simplier way to say that is:
var Qry = from c in Customers
where !c.Orders.Any()
select c;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.