Skip to content

Can't include constant GUIDs in the projection #35826

Closed

Description

@roji

When including a constant Guid in a projected, unmapped type (e.g. DTO), EF seems to treat it as text and fails loading.

Minimal repro:

await using var context = new BlogContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

context.Blogs.Add(new Blog { Id = Guid.NewGuid() });
await context.SaveChangesAsync();

var query = await context.Blogs
    .Select(a => new BlogVm
    {
        Id = a.Id,
        SomeInt = 8, // This works
        SomeViewModelReference = Guid.Empty, // This fails
    })
    .ToListAsync();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();
}

public class Blog
{
    public Guid Id { get; set; }
}

public class BlogVm
{
    public Guid Id { get; set; }
    public Guid SomeViewModelReference { get; set; }
    public int SomeInt {get; set;}
}

SQL:

SELECT [b].[Id], 8 AS [SomeInt], '00000000-0000-0000-0000-000000000000' AS [SomeViewModelReference]
FROM [Blogs] AS [b]

Exception:

Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.Guid' to type 'System.String'.
   at Microsoft.Data.SqlClient.SqlBuffer.get_Guid()
   at Microsoft.Data.SqlClient.SqlDataReader.GetGuid(Int32 i)
   at lambda_method23(Closure, QueryContext, DbDataReader, ResultContext, SingleQueryResultCoordinator)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync() in /Users/roji/projects/efcore/src/EFCore.Relational/Query/Internal/SingleQueryingEnumerable.cs:line 364

Of course, when investigating this check other types as well, as this is likely part of a larger problem.

Originally reported by @espentveit in npgsql/efcore.pg#3507

Activity

  1. added theissue type on Mar 21, 2025
  2. added this to the Backlog milestone on Mar 23, 2025
  3. Aziz-Dhiab commented on Oct 5, 2026

    @Aziz-Dhiab
    Contributor

    Hey, I've done some investigations and the issue is that without a typed variable or a column type to compare to, constant literals like '00000000-0000-0000-0000-000000000000' will be of type varchar which causes the error because the C# Guid variable expects a uniqueidentifier.

    Same thing happens for any constant (not NewExpression) that the representation/write literal type (varchar) is different than the expected type. All these cause the same issue: default(Guid), default(DateTime), DateTime.MinValue, DateTime.MaxValue, TimeSpan.Zero

    Some potential fixes:

    Option1: For select projection transform any SqlConstantExpression into a convert SqlUnaryExpression to cast it in the database (SELECT CAST('00000000-0000-0000-0000-000000000000' AS uniqueidentifier) AS [SomeViewModelReference]).
    I think this should be done to Guid/TimeSpan/DateTime/DateTimeOffset as they can cause issues and it would be weird and unnecessary to add a convert to numeric types

    Options2: Make all constant select projection evaluated client-side. This is a much bigger change but it already happens when an expression translation fails. for example this code will not give an error

    var res = context.BasicTypesEntities
        .Select(b => new
        {
            EmptyGuid = Guid.Empty,
            ExistingGuid = b.Guid,
            DateTime = new DateTime(2020, 1, 1),
        })
        .ToList();

    And will generate this sql

    SELECT [b].[Guid]
    FROM [BasicTypesEntities] AS [b]

    Option3: I don't like this option but we could make ReadGuid/ReadReadDateTime... methods in BufferedDataReader try to parse from strings if the cast fails but this could potentially cause a mismatch if the SQL parsing differs from the C# parsing

    @roji let me know if you approve of a solution and I can try to make a pull request

  4. Aziz-Dhiab commented on Oct 5, 2026

    @Aziz-Dhiab
    Contributor

    Note: replacing Guid.Empty with new Guid() is a possible workaround and will not cause an error

  5. Aziz-Dhiab commented on Oct 5, 2026

    @Aziz-Dhiab
    Contributor

    NVM, I think I've done a lot of overthinking and the issue is simply is that Guid/DateTime/DateTimeOffset/TimeSpan/DateOnly/TimeOnly TypeMapping don't override GenerateNonNullSqlLiteral like byte and long

    Edit: Adding a cast to every constant Guid and date type will add so many casts and will not work with temporal tables

  6. added a commit that references this issue on Oct 9, 2026
    2b99285
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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions