dotnet / dotnet/efcore

We don't know how to bind property to OPENJSON subquery in some scenarios

Open
#33,215 0 comments 0 reactions 0 assignees View on GitHub
area-query
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

For future follow up:

```cs
var query2 = (from b1 in ctx.Blogs
from b2 in ctx.Blogs
where b1.Posts.Contains(b2.Posts.FirstOrDefault())
select new { b1, b2 }).ToList();

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

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Repro;Trusted_Connection=True;MultipleActiveResultSets=true");
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity().OwnsMany(b => b.Posts, b => { b.ToJson(); });
}
}

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

public class Post
{
public int Foo { get; set; }
public string Title { get; set; }
}
```

throws:

```
System.Collections.Generic.KeyNotFoundException : The given key 'EmptyProjectionMember' was not present in the dictionary.

Stack Trace: 
Dictionary`2.get_Item(TKey key)
SelectExpression.GetProjection(ProjectionBindingExpression projectionBindingExpression) line 1414
RelationalSqlTranslatingExpressionVisitor.BindProperty(StructuralTypeReferenceExpression typeReference, IProperty property) line 1367
RelationalSqlTranslatingExpressionVisitor.TryBindMember(Expression source, MemberIdentity member, Expression& expression, IPropertyBase& property) line 1257
RelationalSqlTranslatingExpressionVisitor.TryBindMember(Expression source, MemberIdentity member, Expression& expression) line 1227
RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) line 769
SqlServerSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) line 202
RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) line 840
SqlServerSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) line 202
RelationalSqlTranslatingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression) line 422
<35 more frames...>
```

We are trying to rewrite this to entity equlity. Source we try to bind is:

```
SELECT TOP(1) p1.Foo
FROM OPENJSON(b0.Posts, '') WITH (Foo int 'Foo', Title nvarchar(max) 'Title') AS p1
ORDER BY CAST(p1.key AS int) ASC
```

and the property is Title.

This is likely invalid scenario (JSON entity comparison), but there might be similar cases like this that are valid, but still fail currently - need to investigate further

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.