Can't include constant GUIDs in the projection
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
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:
```c#
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 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:
```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 https://github.com/npgsql/efcore.pg/issues/3507
Contributor guide
Assessment
This issue has not been assessed yet.