我在Entity Framework 7 RC1上使用LINQ左外连接。我们必须使用变通方法,因为左连接未正确实现,请参阅Left Outer Join with Entity Framework Core
var customers = from customer in _db.Customer
join postcode in _db.Postcode
on customer.PostcodeID equals postcode.PostcodeID into custPCTmp
from custPC in custPCTmp.DefaultIfEmpty()
select new
{
// Workaround for EF7 RC1.
Customer = customer,
CustPC = custPC
};
// Workaround for EF7 RC1.
model.CustomersList = new List<CustomerListItemViewModel>();
foreach (var cust in customers)
{
CustomerListItemViewModel custVM = new CustomerListItemViewModel()
{
CustomerID = cust.Customer.CustomerID,
Name = cust.Customer.Name,
Address = cust.Customer.Address,
Town = cust.CustPC == null ? string.Empty : cust.CustPC.Town,
Postcode = cust.CustPC == null ? string.Empty : cust.CustPC.Postcode
};
model.CustomersList.Add(custVM);
}
我期待这样的结果(注意前3行应该有相同的城镇和邮政编码):
Name Address Town Postcode
---------------------------------------
Name 1 Address 1 Town 1 Postcode 1
Name 2 Address 2 Town 1 Postcode 1
Name 3 Address 3 Town 1 Postcode 1
Name 4 Address 4 Town 4 Postcode 4
但是我得到了以下结果(重复第一条记录,三次):
Name Address Town Postcode
--------------------------------------
Name 1 Address 1 Town 1 Postcode 1
Name 1 Address 1 Town 1 Postcode 1
Name 1 Address 1 Town 1 Postcode 1
Name 4 Address 4 Town 4 Postcode 4
我可以看到它是由于客户与PostcodeID上的邮政编码的连接,但为什么它会像这样重复?数据库中的数据看起来很好。
亲切的问候,
Rasika