Skip to content

NumberToBytesConverter on ulong RowVersion property fails with .Include query #12518

Closed

Description

@SimonCropp

Sorry about the detail. but this has a few moving pieces.

(TLDR run this test in the repro)

Scenario

public class Parent
{
    public Guid Id { get; set; } = Guid.NewGuid();
    public Guid? ChildId { get; set; }
    public Child Child { get; set; }
}
public class Child
{
    public Guid Id { get; set; } = Guid.NewGuid();
    public ulong ULongRowVersion { get; set; }
    public Guid ParentId { get; set; }
    public Parent Parent { get; set; }
}
var child = modelBuilder.Entity<Child>();
child.HasOne(_ => _.Parent)
   .WithOne(_ => _.Child)
   .HasForeignKey<Parent>(_ => _.ChildId);
child.Property(x => x.ULongRowVersion)
   .HasConversion(new NumberToBytesConverter<ulong>())
   .IsRowVersion()
   .IsRequired()
   .HasColumnType("RowVersion");

modelBuilder.Entity<Parent>();

image

  • Data: single parent, no child
var parent = new Parent();
context.Add(parent);
context.SaveChanges();
  • execute a query FirstOrDefault query on Parent and .Include the Child property
var firstOrDefault = context.Parents
       .Include(x => x.Child)
       .FirstOrDefault();

Outcome

InvalidOperationException in NumberToBytesConverter.ReverseLong.

System.InvalidOperationException : An exception occurred while reading a database value for property 'Child.ULongRowVersion'. See the inner exception for more information.
---- System.IndexOutOfRangeException : Index was outside the bounds of the array.
   at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityMaterializerSource.ThrowReadValueException[TValue](Exception exception, Object value, IPropertyBase property)
   at lambda_method(Closure , DbDataReader )
   at Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__17`2.MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Tests.ULongRowVersion() in C:\Code\EfRowVersionRepro\DataModel\Tests.cs:line 46
----- Inner Stack Trace -----
   at Microsoft.EntityFrameworkCore.Storage.ValueConversion.NumberToBytesConverter`1.ReverseLong(Byte[] bytes)
   at lambda_method(Closure , DbDataReader )

The strange thing is, that with my understanding of the above scenario, NumberToBytesConverter should never be called since there are no rows in that table.

Repro

https://github.com/SimonCropp/EfRowVersionRepro

The above failing scenario is in the ULongRowVersionContext and can be executed in the Tests.ULongRowVersion() method.

There are also two other working scenarios.

Using BytesRowVersion

This scenario still uses a ulong for the row version, but with a custom. ULongRowVersionWithWorkAroundContext and can be executed in the Tests.ULongRowVersionWithWorkAround() method.

ULongToBytesConverter is a clone of NumberToBytesConverter. When debugging the exception was occurring in the code generated by the custom expressions, so it made it very difficult to understand what the problem was. When i initially created ULongToBytesConverter i got the same exception as with NumberToBytesConverter. But since i was able to debug i was able to see where the error was occurring and add a workaround.

static ulong ToNumber(byte[] bytes)
{
    if (bytes == null)
    {
        return 0;
    }
    #region check added to avoid exception
    if (bytes.Length == 0)
    {
        return 0;
    }
    #endregion

    if (BitConverter.IsLittleEndian)
    {
        bytes = ReverseLong(bytes);
    }

    return BitConverter.ToUInt64(bytes, 0);
}

Note that i have no idea why this works ;)

Further technical details

Activity

  1. ajcvickers commented on Jul 2, 2018

    @ajcvickers
    Contributor

    Notes for triage: NumberToBytesConverter is being called from query with a zero-length byte array, which should never happen even if there are rows in the database. Queries "look" the same in both cases:
    Working query log (property is byte[]):

    dbug: Microsoft.EntityFrameworkCore.Query[10107]
          => Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor
          (QueryContext queryContext) => IEnumerable<Parent> _InterceptExceptions(
              source: IEnumerable<Parent> _TrackEntities(
                  results: IEnumerable<Parent> _ToSequence(() => Parent FirstOrDefault(IEnumerable<Parent> _Select(
                              source: IEnumerable<TransparentIdentifier<Parent, Child>> _ShapedQuery(
                                  queryContext: queryContext,
                                  shaperCommandContext: SelectExpression:
                                      SELECT TOP(1) [x].[Id], [x].[ChildId], [x.Child].[Id], [x.Child].[ULongRowVersion]
                                      FROM [Parent] AS [x]
                                      LEFT JOIN [Child] AS [x.Child] ON [x].[ChildId] = [x.Child].[Id],
                                  shaper: TypedCompositeShaper<BufferedOffsetEntityShaper<Parent>, Parent, BufferedOffsetEntityShaper<Child>, Child, TransparentIdentifier<Parent, Child>>),
                              selector: (TransparentIdentifier<Parent, Child> t1) => Parent _Include(
                                  queryContext: queryContext,
                                  entity: t1.Outer,
                                  included: new object[]{ t1.Inner },
                                  fixup: (QueryContext queryContext | Parent entity | object[] included) =>
                                  {
                                      void queryContext.QueryBuffer.StartTracking(
                                          entity: entity,
                                          entityType: EntityType: Parent)
                                      return !(bool ReferenceEquals(included[0], null)) ?
                                      {
                                          void queryContext.QueryBuffer.StartTracking(
                                              entity: included[0],
                                              entityType: EntityType: Child)
                                          void SetRelationshipSnapshotValue(
                                              stateManager: queryContext.StateManager,
                                              navigation: Parent.Child,
                                              entity: entity,
                                              value: included[0])
                                          return void SetRelationshipSnapshotValue(
                                              stateManager: queryContext.StateManager,
                                              navigation: Child.Parent,
                                              entity: included[0],
                                              value: entity)
                                      }
                                       :
                                      {
                                          void SetRelationshipIsLoaded(
                                              stateManager: queryContext.StateManager,
                                              navigation: Parent.Child,
                                              entity: entity)
                                          return default(void)
                                      }
                                  }
                              )))),
                  queryContext: Unhandled parameter: queryContext,
                  entityTrackingInfos: { itemType: Parent },
                  entityAccessors: List<Func<Parent, object>>
                  {
                      Func<Parent, Parent>,
                  }
              ),
              contextType: BloggingContext,
              logger: DiagnosticsLogger<Query>,
              queryContext: Unhandled parameter: queryContext)
    

    Broken query log:

    dbug: Microsoft.EntityFrameworkCore.Query[10107]
          => Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor
          (QueryContext queryContext) => IEnumerable<Parent> _InterceptExceptions(
              source: IEnumerable<Parent> _TrackEntities(
                  results: IEnumerable<Parent> _ToSequence(() => Parent FirstOrDefault(IEnumerable<Parent> _Select(
                              source: IEnumerable<TransparentIdentifier<Parent, Child>> _ShapedQuery(
                                  queryContext: queryContext,
                                  shaperCommandContext: SelectExpression:
                                      SELECT TOP(1) [x].[Id], [x].[ChildId], [x.Child].[Id], [x.Child].[ULongRowVersion]
                                      FROM [Parent] AS [x]
                                      LEFT JOIN [Child] AS [x.Child] ON [x].[ChildId] = [x.Child].[Id],
                                  shaper: TypedCompositeShaper<BufferedOffsetEntityShaper<Parent>, Parent, BufferedOffsetEntityShaper<Child>, Child, TransparentIdentifier<Parent, Child>>),
                              selector: (TransparentIdentifier<Parent, Child> t1) => Parent _Include(
                                  queryContext: queryContext,
                                  entity: t1.Outer,
                                  included: new object[]{ t1.Inner },
                                  fixup: (QueryContext queryContext | Parent entity | object[] included) =>
                                  {
                                      void queryContext.QueryBuffer.StartTracking(
                                          entity: entity,
                                          entityType: EntityType: Parent)
                                      return !(bool ReferenceEquals(included[0], null)) ?
                                      {
                                          void queryContext.QueryBuffer.StartTracking(
                                              entity: included[0],
                                              entityType: EntityType: Child)
                                          void SetRelationshipSnapshotValue(
                                              stateManager: queryContext.StateManager,
                                              navigation: Parent.Child,
                                              entity: entity,
                                              value: included[0])
                                          return void SetRelationshipSnapshotValue(
                                              stateManager: queryContext.StateManager,
                                              navigation: Child.Parent,
                                              entity: included[0],
                                              value: entity)
                                      }
                                       :
                                      {
                                          void SetRelationshipIsLoaded(
                                              stateManager: queryContext.StateManager,
                                              navigation: Parent.Child,
                                              entity: entity)
                                          return default(void)
                                      }
                                  }
                              )))),
                  queryContext: Unhandled parameter: queryContext,
                  entityTrackingInfos: { itemType: Parent },
                  entityAccessors: List<Func<Parent, object>>
                  {
                      Func<Parent, Parent>,
                  }
              ),
              contextType: BloggingContext,
              logger: DiagnosticsLogger<Query>,
              queryContext: Unhandled parameter: queryContext)
    
  2. added this to the milestone on Jul 6, 2018
  3. modified the milestones: , 3.0.0 on Aug 3, 2018
  4. SimonCropp commented on Jan 30, 2019

    @SimonCropp
    ContributorAuthor

    doing a cleanup of my repos. can u take a copy of what u need from https://github.com/SimonCropp/EfRowVersionRepro/ so i can delete it

  5. ajcvickers commented on Jan 30, 2019

    @ajcvickers
    Contributor

    @SimonCropp I think we have what we need.

  6. SimonCropp commented on Feb 2, 2019

    @SimonCropp
    ContributorAuthor

    @ajcvickers cool. thanks for the followup

  7. replaysMike commented on Feb 17, 2019

    @replaysMike

    ah man I hit this too, looking forward to a fix

  8. replaysMike commented on Feb 17, 2019

    @replaysMike

    Providing a temporary workaround that worked in my case:

    on this table:

    public class MyTable {
      public ulong RowVersion { get; set; }
    }
    

    using this builder config:

    builder.Entity<MyTable>()
                    .Property(p => p.RowVersion)
                    .HasConversion<byte[]>()
                    .IsRowVersion();
    
    migrationBuilder.AddColumn<byte[]>(
                    name: "RowVersion",
                    table: "MyTable",
                    nullable: false,
                    defaultValue: new byte[] { });
    

    manually changing the default value to a non-zero length array in the migration fixes it:

    migrationBuilder.AddColumn<byte[]>(
                    name: "RowVersion",
                    table: "MyTable",
                    nullable: false,
                    defaultValue: new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
    
  9. 18 remaining items

  10. modified the milestones: Backlog, on Aug 26, 2020
  11. added 2 commits that reference this issue on Aug 26, 2020
    205175a
    9bbaf50
  12. ghost closed this as completedin #22257on Aug 27, 2020
  13. ghost added a commit that references this issue on Aug 27, 2020
    cd75030
  14. modified the milestones: , 5.0.0 on Nov 7, 2020
  15. billybraga commented on Mar 10, 2021

    @billybraga
    Contributor

    I am having this issue in 5.0.4. I can't seem to figure out if the bug was fixed (can't find a commit in here that addresses the issue).

  16. ajcvickers commented on Mar 12, 2021

    @ajcvickers
    Contributor

    @billybraga If this isn't working for you with 5.0.4, then please open a new issue and attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

  17. billybraga commented on Mar 19, 2021

    @billybraga
    Contributor
  18. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions