dotnet / dotnet/efcore

Entities with JSON owned entities can't be queried out with FromSql

Open
#36,282 2 comments 1 reaction 0 assignees View on GitHub
area-json area-query
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

For an entity type that has JSON owned entities, the following fails:

```c#
var items = await context.Blogs.FromSql($"WITH query AS (SELECT * FROM Blogs) SELECT * FROM query").ToListAsync();
```

It seems like when applying the final projection, we compose an additional SELECT on top:

```sql
SELECT b.Id, b.Name, b.Owned
FROM WITH query AS (SELECT * FROM Blogs) SELECT * FROM query
```

... and this (correctly) causes a non-composable SQL failure. We should not need to compose this extra SELECT on top.

With the focus on complex types for mapping JSON in EF 10, owned entities are getting de-prioritized. Given that, and given that we haven't seen many reports, i'll put this on the backlog for now.

Repro

```c#
await using var context = new BlogContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

var items = await context.Blogs.FromSql($"WITH query AS (SELECT * FROM Blogs) SELECT * FROM query").ToListAsync();

public class BlogContext : DbContext
{
public DbSet Blogs { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false")
.LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging();

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity().OwnsOne(b => b.Owned).ToJson();
}
}

public class Blog
{
public int Id { get; set; }
public string Name { get; set; }

public Owned Owned { get; set; }
}

public class Owned
{
public int OwnedProperty { get; set; }
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.