Skip to content

Exception when using FromSql on entity with ComplexProperty #32699

Description

@kimbirkelund

Reproduction: EfComplexPropertyFromSqlTests.zip

Given an entity like the following:

public class Entity
{
    public required ComplexPropertyType ComplexProperty { get; set; }

    public Guid Id { get; set; } = Guid.NewGuid();
}

[ComplexType]
public record ComplexPropertyType(
    string Property1,
    string Property2);

Which works fine when inserting and querying normally.

The problem occurs when trying to execute a FromSql query like so:

db.Entities.FromSql($"""SELECT * FROM Entities""").ToList();

Or similar (see the DoThis service in the attached code).

The following exception is thrown when running the attached code:

System.Collections.Generic.KeyNotFoundException: The given key 'Table: Entities  Key: PK_Entities {'Id'} PrimaryKey' was not present in the dictionary.
   at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
   at Microsoft.EntityFrameworkCore.Query.SqlExpressions.SelectExpression.GenerateComplexPropertyShaperExpression(StructuralTypeProjectionExpression containerProjection, IComplexProperty complexProperty)
   at Microsoft.EntityFrameworkCore.Query.StructuralTypeProjectionExpression.BindComplexProperty(IComplexProperty complexProperty)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.BindComplexProperty(StructuralTypeReferenceExpression typeReference, IComplexProperty complexProperty)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TryBindMember(Expression source, MemberIdentity member, Expression& expression, IPropertyBase& property)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TryBindMember(Expression source, MemberIdentity member, Expression& expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitMember(MemberExpression memberExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TranslateInternal(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TranslateProjection(Expression expression, Boolean applyDefaultTypeMapping)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.VisitNew(NewExpression newExpression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.Translate(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at EfComplexPropertyFromSqlTests.DoThis.Log[T](String name, IQueryable`1 queryable) in C:\Users\kim\source\tests\EfComplexPropertyFromSqlTests\EfComplexPropertyFromSqlTests\DoThis.cs:line 49
   at EfComplexPropertyFromSqlTests.DoThis.ExecuteAsync(CancellationToken stoppingToken) in C:\Users\kim\source\tests\EfComplexPropertyFromSqlTests\EfComplexPropertyFromSqlTests\DoThis.cs:line 40
   at Microsoft.Extensions.Hosting.Internal.Host.TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)

Provider and version information

EF Core version: 8
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 8.0.100
Operating system: Windows 11

Activity

  1. self-assigned this
    on Jan 10, 2024
  2. added this to the 8.0.x milestone on Jan 11, 2024
  3. added a commit that references this issue on Jan 14, 2024
    46e9b08
  4. added 2 commits that reference this issue on Jan 19, 2024
    81b7a40
    3791459
  5. added a commit that references this issue on Jan 23, 2024
    32886fb
  6. added 2 commits that reference this issue on Jan 23, 2024
    2518773
    290c4ba
  7. modified the milestones: 8.0.x, 8.0.3 on Feb 2, 2024
  8. added a commit that references this issue on Feb 7, 2024
    c5d8f3c
  9. samisq commented on Feb 20, 2024

    @samisq

    I encountered the exact same exception when using FromExpression that maps to a table-Valued function, instead of FromSql, like:

    pubic class MyDbContext : DbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasDbFunction(() => GetEntityWithCalcuationsFunc(Guid.Empty));
        }
    
        public IQueryable<Entity> GetEntityWithCalcuationsFunc(Guid id)
                => FromExpression(() => GetEntityWithCalcuationsFunc(id));
    }
    
    public class Entity
    {
        public required ComplexPropertyType ComplexProperty { get; set; }
    
        public Guid Id { get; set; }
    }
    
    [ComplexType]
    public record ComplexPropertyType(string Property1, string Property2);
    

    Will this fix address it too?

  10. removed their assignment
    on Aug 31, 2024
  11. AlexTankSWO commented on Sep 11, 2024

    @AlexTankSWO

    I am facing the same issue. As soon as I remove my complex type property from my entity, FromSql works as expected.
    We are using EF Core 8.0.1

    But I could see that in 8.0.8 this issue does not occur anymore.

  12. AndriySvyryd commented on Sep 13, 2024

    @AndriySvyryd
    Member

    @samisq No, that's tracked in #34627

  13. 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

No one assigned

    Type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions