asp.net-core - Entity Framework Core 中值对象查询中的额外联接

标签 asp.net-core .net-core entity-framework-core value-objects

在 Entity Framework Core 3.1.3 中,我使用了值对象功能。在查询方面,问题是 T-SQL 中存在额外的左连接。这种额外的连接会导致性能问题。在以下代码中,Student 是实体类型,Address 类是值类型

实体

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
}

数据库上下文

public class ApplicationDbContext : DbContext
{
    public DbSet<Student> Students { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Student>().OwnsOne(e => e.Address);
        base.OnModelCreating(builder);
    }
}

Entity Framework 查询

var list = _dbContext.Students.ToList();

为此 EF 查询生成的 T-SQL:

SELECT [s].[Id], [s].[Name], [t].[Id], [t].[Address_City], 
       [t].[Address_Street], [t].[Address_ZipCode]
FROM [Students] AS [s]
LEFT JOIN (
    SELECT [s0].[Id], [s0].[Address_City], 
           [s0].[Address_Street], [s0].[Address_ZipCode]
    FROM [Students] AS [s0]
    WHERE [s0].[Address_ZipCode] IS NOT NULL OR 
          ([s0].[Address_Street] IS NOT NULL OR 
          [s0].[Address_City] IS NOT NULL)
) AS [t] ON [s].[Id] = [t].[Id]

最佳答案

这是 EF Core 3.0 新查询处理管道引入的错误,很可能与以下重大更改相关 Dependent entities sharing the table with the principal are now optional ,它应该修复一些用户请求的场景,但实际上破坏了许多其他场景。

目前由 #18299: Query on owned entity produces overly complicated SQL 追踪不幸的是,这个问题似乎不会在 3.1 中得到修复,所以人们预计会等待 5.0 的发布。与此同时,您对此无能为力。

关于asp.net-core - Entity Framework Core 中值对象查询中的额外联接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61052328/

相关文章:

asp.net-web-api - MVC 核心 ZipArchive 无效

c# - 如何将 appsetting.json 部分加载到 .NET Core 中的字典中?

c# - 当 T 为类型时,使用 ServiceCollection 配置 IOptions<T>

c# - 如何使用 ASP.Net Core Identity 从登录用户检索 Google 个人资料图片?

c# - ASP.NET Core 3.0 Web API 路由不起作用

c# - 需要 ASP.NET Core 2.0 分页帮助

c# - 从数据库中提取数据时无法转换 SqlGeography

c# - .net 核心 ProtoBuf 上的序列化程序在哪里?

c# - 具有一对多关系的自定义身份用户类在数据库中创建额外的列

entity-framework-core - 配置 EF Core CLI 参数