Skip to content

Commit 0300f55

Browse files
Copilotrenemadsen
andcommitted
Fix: Override GetDataReaderMethod in MySqlJsonTypeMapping to use GetString
MySQL stores JSON as strings, but EF Core's default behavior tries to read them as MemoryStream for complex types. This causes a "No coercion operator is defined between types 'System.String' and 'System.IO.MemoryStream'" error. The fix overrides GetDataReaderMethod() to explicitly return DbDataReader.GetString, ensuring JSON values are read as strings. Co-authored-by: renemadsen <76994+renemadsen@users.noreply.github.com>
1 parent f2abbdc commit 0300f55

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

src/EFCore.MySql/Storage/Internal/MySqlJsonTypeMapping.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Collections.Generic;
66
using System.Data.Common;
77
using System.Linq;
8+
using System.Reflection;
89
using JetBrains.Annotations;
910
using Microsoft.EntityFrameworkCore;
1011
using Microsoft.EntityFrameworkCore.ChangeTracking;
@@ -57,6 +58,9 @@ protected override RelationalTypeMapping Clone(bool? noBackslashEscapes = null,
5758

5859
public abstract class MySqlJsonTypeMapping : MySqlStringTypeMapping, IMySqlCSharpRuntimeAnnotationTypeMappingCodeGenerator
5960
{
61+
private static readonly MethodInfo _getString
62+
= typeof(DbDataReader).GetRuntimeMethod(nameof(DbDataReader.GetString), new[] { typeof(int) });
63+
6064
public MySqlJsonTypeMapping(
6165
[NotNull] string storeType,
6266
[NotNull] Type clrType,
@@ -118,6 +122,14 @@ protected override void ConfigureParameter(DbParameter parameter)
118122
}
119123
}
120124

125+
/// <summary>
126+
/// Returns the method to be used for reading JSON values from the database.
127+
/// MySQL stores JSON as strings, so we use GetString instead of the default GetFieldValue&lt;T&gt;.
128+
/// This prevents EF Core from trying to convert from string to MemoryStream for complex JSON types.
129+
/// </summary>
130+
public override MethodInfo GetDataReaderMethod()
131+
=> _getString;
132+
121133
void IMySqlCSharpRuntimeAnnotationTypeMappingCodeGenerator.Create(
122134
CSharpRuntimeAnnotationCodeGeneratorParameters codeGeneratorParameters,
123135
CSharpRuntimeAnnotationCodeGeneratorDependencies codeGeneratorDependencies)

0 commit comments

Comments
 (0)