LearnEntityFrameworkCore.com - Inheritance - TPT - TPT Generated Database Schema

CSharp · Console

/Program.cs

// @nuget: Microsoft.EntityFrameworkCore.SqlServer
// @nuget: Z.EntityFramework.Extensions.EFCore

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

public class Program
{
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			context.Database.EnsureCreated();
		}
		
		using (var context = new EntityContext())
		{
			context.Animals.Add(new Cat() { Name = "Nala", DateOfBirth = new DateTime(2024, 11, 01), IsIndoor = true, LivesRemaining = 8 });
			context.Animals.Add(new Dog() { Name = "Bengi", DateOfBirth = new DateTime(2017, 04, 01), Breed = "Anything", IsGoodBoy = true });
			context.SaveChanges();		
		}
		
		using (var context = new EntityContext())
		{
			Console.WriteLine(context.Database.GenerateCreateScript());
		}
	}
	
	public class EntityContext : DbContext
	{
		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			optionsBuilder.UseSqlServer(new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()));

			base.OnConfiguring(optionsBuilder);
		}
		
		protected override void OnModelCreating(ModelBuilder modelBuilder)
		{
			modelBuilder.Entity<Animal>()
				.UseTptMappingStrategy()
				.ToTable("Animals");

			modelBuilder.Entity<Cat>()
				.ToTable("Cats");

			modelBuilder.Entity<Dog>()
				.ToTable("Dogs");

			base.OnModelCreating(modelBuilder);
		}
		
		public DbSet<Animal> Animals { get; set; }
		public DbSet<Cat> Cats { get; set; }
		public DbSet<Dog> Dogs { get; set; }
	}

	public abstract class Animal
	{
		public int Id { get; set; }
		public string? Name { get; set; }
		public DateTime DateOfBirth { get; set; }
	}

	public class Cat : Animal
	{
		public bool IsIndoor { get; set; }
		public int LivesRemaining { get; set; }
	}

	public class Dog : Animal
	{
		public string? Breed { get; set; }
		public bool IsGoodBoy { get; set; }
	}
}
;