Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't include constant GUIDs in the projection #35826

Open
roji opened this issue Mar 21, 2025 · 0 comments
Open

Can't include constant GUIDs in the projection #35826

roji opened this issue Mar 21, 2025 · 0 comments

Comments

@roji
Copy link
Member

roji commented Mar 21, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant