dotnet / dotnet/efcore

Improve exceptions for invalid JSON values in JSON column

Open
#35,863 2 comments 0 reactions 0 assignees View on GitHub
area-json customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

### Bug description

This is valid JSON:
```
{
"Access": [
null
]
}
```

But when trying to query a row that contains this column, it produces this error:

```
System.InvalidOperationException
Invalid token type: 'Null'.
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.MaterializeJsonEntityCollection[TEntity,TResult](QueryContext queryContext, Object[] keyPropertyValues, JsonReaderData jsonReaderData, INavigationBase navigation, Func`4 innerShaper)
at lambda_method51(Closure, QueryContext, Object[], JsonReaderData)
at lambda_method50(Closure, QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
```

### Your code

```csharp
Repo at
https://github.com/rogerfar/npgsql-reproduction

public class AppDbContext : DbContext
{
public DbSet Users => Set();

public AppDbContext(DbContextOptions options) : base(options) { }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity(e =>
{
e.HasKey(u => u.Id);
e.OwnsOne(m => m.MetaData, m =>
{
m.ToJson();
m.OwnsMany(u => u.Access);
});
});
}
}

public class User
{
public Int32 Id { get; set; }
public MetaData? MetaData { get; set; }
}

public class MetaData
{
public List? Access { get; set; }
}

public class AccessMetaData
{
public String Name { get; set; }
public Int32 Level { get; set; }
}
```

### Stack traces

```text

```

### Verbose output

```text

```

### EF Core version

9.0.0

### Database provider

Npgsql.EntityFrameworkCore.PostgreSQL

### Target framework

.NET 9.0

### Operating system

_No response_

### IDE

_No response_

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.