efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Extra join in query for value objects in Entity framework Core

Open MohammadAkbari opened this issue 6 years ago • 1 comments

In Entity Framework core 3.1.3, I have used the value object feature. In the query side, the problem is an extra left join exists in TSql. This extra join results problems in terms of performance.

Entities

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; }
}

DbContext

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 query

var list = _dbContext.Students.ToList();

Generated 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]

Further technical details

EF Core version: Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET Core 3.1.1 Operating system: Windows 10 IDE: Visual Studio 2019 16.3

MohammadAkbari avatar Apr 06 '20 03:04 MohammadAkbari

Duplicate of #18299

ajcvickers avatar Apr 06 '20 22:04 ajcvickers