CSharp · Console
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
public abstract class Animal
{
public int Id { get; set; }
public string Name { get; set; } = "";
public DateTime DateOfBirth { get; set; }
}
public sealed class Cat : Animal
{
public bool IsIndoor { get; set; }
public int LivesRemaining { get; set; }
}
public sealed class Dog : Animal
{
public string? Breed { get; set; }
public bool IsGoodBoy { get; set; }
}
public sealed class AppDbContext : DbContext
{
public DbSet<Animal> Animals => Set<Animal>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlite("Data Source=:memory:");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Animal>(b =>
{
b.ToTable("Animals");
b.HasDiscriminator<int>("AnimalType")
.HasValue<Cat>(1)
.HasValue<Dog>(2);
b.HasIndex("AnimalType");
});
}
}
public class Program
{
public static void Main()
{
using var db = new AppDbContext();
db.Database.OpenConnection();
db.Database.EnsureCreated();
Seed(db);
Console.WriteLine("=== 1) Consulta polimórfica (DbSet<Animal>) ===");
var animalsQuery = db.Animals
.OrderBy(a => a.Id)
.Select(a => new
{
a.Id,
a.Name,
a.DateOfBirth,
Tipo = a.GetType().Name,
Discriminador = EF.Property<int>(a, "AnimalType")
});
Console.WriteLine();
Console.WriteLine("=== SQL generado (consulta polimórfica) ===");
Console.WriteLine(animalsQuery.ToQueryString());
var allAnimals = animalsQuery.ToList();
FiddleHelper.WriteTable(allAnimals);
Console.WriteLine();
Console.WriteLine("=== 2) Consulta por derivado (OfType<Cat>) ===");
var catsQuery = db.Animals
.OfType<Cat>()
.OrderBy(a => a.Id)
.Select(a => new
{
a.Id,
a.Name,
a.DateOfBirth,
a.IsIndoor,
a.LivesRemaining,
Discriminador = EF.Property<int>(a, "AnimalType")
});
Console.WriteLine();
Console.WriteLine("=== SQL generado (OfType<Cat>) ===");
Console.WriteLine(catsQuery.ToQueryString());
var cats = catsQuery.ToList();
FiddleHelper.WriteTable(cats);
Console.WriteLine();
Console.WriteLine("=== 3) Hecho: TPH = 1 tabla + filtro por discriminador (sin JOINs) ===");
}
private static void Seed(AppDbContext db)
{
db.Animals.AddRange(
new Cat
{
Name = "Milo",
DateOfBirth = new DateTime(2022, 4, 10),
IsIndoor = true,
LivesRemaining = 9
},
new Dog
{
Name = "Rocky",
DateOfBirth = new DateTime(2020, 9, 3),
Breed = "Labrador",
IsGoodBoy = true
},
new Cat
{
Name = "Luna",
DateOfBirth = new DateTime(2023, 1, 15),
IsIndoor = false,
LivesRemaining = 8
},
new Dog
{
Name = "Max",
DateOfBirth = new DateTime(2021, 6, 20),
Breed = "Beagle",
IsGoodBoy = true
}
);
db.SaveChanges();
}
}