实体框架生成左外连接时,它应该做内连接(多个表)
本文关键字:连接 框架 实体 | 更新日期: 2023-09-27 18:09:19
我有以下奇怪的行为:
public class Result
{
[Key]
public int Id { get; set; }
public int RuleId { get; set; }
public int UserId { get; set; }
[ForeignKey("RuleId")]
public virtual Rule Rule { get; set; }
[ForeignKey("UserId ")]
public virtual User User { get; set; }
}
public class Rule
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
// More columns
}
public class User
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
// More columns
}
如果我这样做:
ctx.Results.AsQueryable().Select(r => new { r.Rule.Name } ).ToList();
在SQL Server中执行的查询对Rule:
进行内部连接。SELECT
[Extent1].[RuleId] AS [RuleId],
[Extent2].[Name] AS [Name]
FROM [dbo].[result] AS [Extent1]
INNER JOIN [dbo].[rule] AS [Extent2] ON [Extent1].[RuleId] = [Extent2].[Id]
但
ctx.Results.AsQueryable().Select(r => new { rn = r.Rule.Name, un = r.User.Name } ).ToList();
执行的查询对rule执行inner join,但对User执行OUTER join。
SELECT
[Extent1].[UserId] AS [UserId],
[Extent2].[Name] AS [Name],
[Extent3].[Name] AS [Name1]
FROM [dbo].[result] AS [Extent1]
INNER JOIN [dbo].[rule] AS [Extent2] ON [Extent1].[RuleId] = [Extent2].[Id]
LEFT OUTER JOIN [dbo].[user] AS [Extent3] ON [Extent1].[UserId] = [Extent3].[Id]
这肯定是错的吗?
答案是:实体框架存在Bug。下载最新版本,它们都是内连接