Open cyungmann opened 1 month ago
In case it's helpful, here are copies of the code files:
Program.cs
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using SqliteJsonTest;
await using var conn = new SqliteConnection(new SqliteConnectionStringBuilder
{
DataSource = ":memory:",
}.ConnectionString);
await conn.OpenAsync();
await using var db = new WidgetContext(new DbContextOptionsBuilder<WidgetContext>().UseSqlite(conn).Options);
await db.Database.EnsureCreatedAsync();
var widget = await db.Widgets.SingleAsync();
WidgetContext.cs
using Microsoft.EntityFrameworkCore;
namespace SqliteJsonTest;
internal sealed class WidgetContext : DbContext
{
public DbSet<Widget> Widgets { get; set; }
public WidgetContext(DbContextOptions options) : base(options)
{
}
}
Widget.cs
using System.Text.Json;
namespace SqliteJsonTest;
internal sealed class Widget
{
public long Id { get; set; }
public JsonElement Metadata { get; set; }
}
SqliteJsonTest.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.8" />
</ItemGroup>
</Project>
related to / dupe of https://github.com/dotnet/efcore/issues/28871 we could consider throwing a better exception in the meantime
@maumar using Microsoft.EntityFrameworkCore.Sqlite 7.0.20, I get System.InvalidOperationException: 'The property 'Widget.Metadata' could not be mapped because it is of type 'JsonElement', which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'
, which seems better.
yeah, we should get back to something similar. Looks like we bypass any validation and try to construct the shaper for JsonElement as if it were a regular POCO entity mapped to json (and resulting in nasty error about MemoryStream).
We do use clr type JsonElement
to mark column as json (as opposed to regular string in sqlite/sql server). Maybe that's why validation gets fooled.
Getting exception
System.InvalidOperationException: 'No coercion operator is defined between types 'System.IO.MemoryStream' and 'System.Text.Json.JsonElement'.'
when trying to pull back records withJsonElement
properties.Stacktrace:
Code is here: SqliteJsonTest.zip
EF Core version: 8.0.8 Database provider: Microsoft.EntityFrameworkCore.Sqlite Target framework: .NET 8.0 Operating system: Windows 10 Enterprise 22H2 IDE: Visual Studio 2022 17.11.4