Skip to content

Instantly share code, notes, and snippets.

@dario-l
Created May 28, 2025 15:08
Show Gist options
  • Save dario-l/7fe437f9101c6962828ab4905d853fe4 to your computer and use it in GitHub Desktop.
Save dario-l/7fe437f9101c6962828ab4905d853fe4 to your computer and use it in GitHub Desktop.
OwnsOne and ComplexProperty mixed mapping results in projecting all columns from data table
// See https://aka.ms/new-console-template for more information
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
var serviceCollection = new ServiceCollection();
serviceCollection.AddDbContext<DatabaseContext>(c => c.UseSqlite("Data Source=:memory:"));
var serviceProvider = serviceCollection.BuildServiceProvider();
var dbContext = serviceProvider.GetService<DatabaseContext>();
dbContext.Database.Migrate();
var query = dbContext.Models.AsNoTracking()
.Where(x => x.ID > 1)
.Select(x => new
{
x.Name,
x.DateClass.VDate
});
Console.WriteLine(query.ToQueryString());
Console.WriteLine("\r\nDone.");
public class DatabaseContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var m = modelBuilder.Entity<Model>();
m.Property(x => x.ID);
m.Property(x => x.Name);
m.Property(x => x.Date);
m.OwnsOne(p => p.DateRecord);
m.ComplexProperty(p => p.DateClass);
}
public DbSet<Model> Models { get; set; }
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
}
public class Model
{
public int ID { get; set; }
public string Name { get; set; }
public DateTimeOffset Date { get; set; }
public ValidClass DateClass { get; set; }
public ValidRecord DateRecord { get; set; }
}
public readonly record struct ValidStruct(DateTimeOffset YDate);
public sealed record ValidRecord(DateTimeOffset XDate);
public sealed class ValidClass : IEquatable<ValidClass>
{
public DateTimeOffset VDate { get; set; }
public bool Equals(ValidClass? other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return VDate.Equals(other.VDate);
}
public override bool Equals(object? obj)
{
return ReferenceEquals(this, obj) || obj is ValidClass other && Equals(other);
}
public override int GetHashCode()
{
return VDate.GetHashCode();
}
};
@dario-l
Copy link
Author

dario-l commented May 28, 2025

Selecting only 2 columns generates query with all columns:

    .Select(x => new
    {
        x.Name,
        x.DateClass.VDate
    });
SELECT "m"."Name", "m"."ID", "m"."Date", "m"."DateClass_VDate", "m"."DateRecord_XDate"
FROM "Models" AS "m"
WHERE "m"."ID" > 1

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