EF - Table Per Concrete

CSharp · Console

/Program.cs

// @nuget: EntityFramework

using System;
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
					
public class Program
{
	public static void Main()
	{
		using (var context = new EntityContext())
		{
			//context.Database.Log = Console.Write;
		    Student student = new Student()
		    {
		        Id = 1,
		        FullName = "Mark",
		        EnrollmentDate = DateTime.Now
		    };

		    Teacher teacher = new Teacher()
		    {
		        Id = 2,
		        FullName = "John",
		        HireDate = DateTime.Now
		    };

		    context.People.Add(student);
		    context.People.Add(teacher);

		    context.SaveChanges();
			
			var query = context.People.ToString();
			
			Console.WriteLine(query);
		}
	}
	
	public class EntityContext : DbContext
	{
		public EntityContext() : base(FiddleHelper.GetConnectionStringSqlServer())
		{

		}
		
    	public DbSet<Person> People { get; set; }

    	protected override void OnModelCreating(DbModelBuilder modelBuilder)
    	{
        	modelBuilder.Entity<Student>().Map(m =>
        	{
            	m.MapInheritedProperties();
            	m.ToTable("Students");
        	});

        	modelBuilder.Entity<Teacher>().Map(m =>
        	{
            	m.MapInheritedProperties();
            	m.ToTable("Teachers");
        	});
    	}
	}
	
	public abstract class Person
	{
    	[DatabaseGenerated(DatabaseGeneratedOption.None)]
    	public int Id { get; set; }
    	public string FullName { get; set; }
	}

	public class Student : Person
	{
    	public DateTime EnrollmentDate { get; set; }
	}

	public class Teacher : Person
	{
    	public DateTime HireDate { get; set; }
	}
}
;