Quantcast
Channel: entityframework Discussions Rss Feed
Viewing all articles
Browse latest Browse all 1793

New Post: Mixing TPC and TPH in one Class Hierarchy

$
0
0
Hey Christian,

Here is some sample code that achieves what you are after.

BTW MapInheritedProperties is what identifies that it should be TPC rather than TPT (i.e. any inherited properties are mapped to the specified table rather than stored in a base table).
using System.Data.Entity;

namespace InheritanceSample
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new MyContext())
            {
                db.Entities.Add(new concreteA { Id = 1, PropertyForA = "AAA" });
                db.Entities.Add(new concreteB1 { Id = 2, PropertyForB = "BBB", PropertyForB1 = "111" });
                db.Entities.Add(new concreteB2 { Id = 3, PropertyForB = "BBB", PropertyForB2 = "222" });
                db.SaveChanges(); 
            }
        }
    }

    public class MyContext : DbContext
    {
        public DbSet<Entity> Entities { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Entity>()
                .Map<concreteA>(m =>
                    {
                        m.ToTable("TableA");
                        m.MapInheritedProperties();
                    })
                .Map<concreteB1>(m =>
                {
                    m.ToTable("TableB");
                    m.Requires("Type").HasValue("1");
                    m.MapInheritedProperties();
                })
                .Map<concreteB2>(m =>
                {
                    m.ToTable("TableB");
                    m.Requires("Type").HasValue("2");
                    m.MapInheritedProperties();
                });
        }
    }

    public abstract class Entity
    {
        public int Id { get; set; }
    }

    public class concreteA : Entity
    {
        public string PropertyForA { get; set; }
    }

    public abstract class EntityB : Entity
    {
        public string PropertyForB { get; set; }
    }

    public class concreteB1 : EntityB
    {
        public string PropertyForB1 { get; set; }
    }

    public class concreteB2 : EntityB
    {
        public string PropertyForB2 { get; set; }
    }
}
~Rowan

Viewing all articles
Browse latest Browse all 1793

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>