无法理解这种EF Core 2关系的行为

时间:2018-04-17 10:38:13

标签: .net-core entity-framework-core relationships .net-core-2.0

首先使用EF核心2代码,我有4个实体:

客户拥有一系列联系人和地址。 客户有一个PaymenTerm,PaymentTerm有一组客户(没必要,因为我不想通过PaymentTerm进行搜索)。

我希望通过“联系人和地址”及其PaymentTerm检索所有客户:

Enter 'secret' to see the div.
<br>
<input type="text" onkeyup="check_password (this);">
<br>
<div id="hidden_div" style="display: none;">I was hidden until the right password was entered.</div>

这些是dbcontext配置: 客户:

var customers = await _context.Customers
                              .Include(c => c.Contacts)
                              .Include(c => c.Addresses)
                              .Include(c => c.PaymentTerm)
                              .ToListAsync();

PaymentTerm:

x.HasMany(e => e.Contacts)
                .WithOne(e => e.Customer)
                .OnDelete(DeleteBehavior.Cascade);
x.HasMany(e => e.Addresses)
                .WithOne(e => e.Customer)
                .OnDelete(DeleteBehavior.Cascade);

问题:查询不返回任何记录。这是生成的SQL查询:

x.HasMany(e => e.Customers)
                .WithOne(e => e.PaymentTerm)
                .OnDelete(DeleteBehavior.Restrict);

没有添加联系人和地址的联接,也没有返回记录。

如果我删除了SELECT [c].[CustomerId], [c].[Cif], [c].[CommercialName], [c].[Created], [c].[CreatedBy], [c].[CustomerName], [c].[Deleted], [c].[DeletedBy], [c].[DeletedDate], [c].[Modified], [c].[ModifiedBy], [c].[PaymentTermId], [c].[TaxFree], [c].[Vat], [t].[PaymentTermId], [t].[Created], [t].[CreatedBy], [t].[Days], [t].[Deleted], [t].[DeletedBy], [t].[DeletedDate], [t].[Modified], [t].[ModifiedBy], [t].[PaymentTermName] FROM [Customers] AS [c] INNER JOIN ( SELECT [p].[PaymentTermId], [p].[Created], [p].[CreatedBy], [p].[Days], [p].[Deleted], [p].[DeletedBy], [p].[DeletedDate], [p].[Modified], [p].[ModifiedBy], [p].[PaymentTermName] FROM [PaymentTerms] AS [p] WHERE [p].[Deleted] = 0 ) AS [t] ON [c].[PaymentTermId] = [t].[PaymentTermId] WHERE [c].[Deleted] = 0 ORDER BY [c].[CustomerId] ,那么带有联系人和地址的客户将被正常退回。

拜托,你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

您的查询正在进行内部联接,而您必须使用“左联接”。您可以使用DefaultIfEmpty实现此目的。