Created
May 28, 2025 15:08
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Selecting only 2 columns generates query with all columns: