Repository navigation
Description
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
Reacted by Robert Giesecke and Rasmus Hansen
Activity
Aziz-Dhiab commentedon Oct 5, 2026
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 typevarcharwhich causes the error because the C#Guidvariable expects auniqueidentifier.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.ZeroSome 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
And will generate this sql
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
Aziz-Dhiab commentedon Oct 5, 2026
Note: replacing
Guid.Emptywithnew Guid()is a possible workaround and will not cause an errorAziz-Dhiab commentedon Oct 5, 2026
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
GenerateNonNullSqlLiterallike byte and longEdit: Adding a cast to every constant Guid and date type will add so many casts and will not work with temporal tables
Fix constant guid select (dotnet#39200)