Elisabeth
Elisabeth

Reputation: 21206

I need a mix of table per hierarchy or type in entity framework

I have 3 entities and I want to use them for EF as POCO`s:

TimeTable is the base class for Period and LessonPlanner classes.

How can I use/map these 3 classes with EF 5.0 or higher?

I want to get 2 sql tables created: Period and LessonPlanner.

EF supports only Table per hierarchy or Table per type.

Either I get one table containing all properties as fields OR I get 3 separated tables.

I just want 2 tables whatever approach I have to take I do not care: Database/Model/Code first...

public class TimeTable
{
    public int Id { get; set; }
    public int LessonNumber { get; set; }
    public string SchoolclassNumberForSunday { get; set; }
    public string SchoolclassNumberForMonday { get; set; }
    public string SchoolclassNumberForTuesday { get; set; }
    public string SchoolclassNumberForWednesday { get; set; }
    public string SchoolclassNumberForThursday { get; set; }
    public string SchoolclassNumberForFriday { get; set; }
    public string SchoolclassNumberForSaturday { get; set; }
}

public class Period : TimeTable
{        
    public enum WeekType
    {
        A,
        AB,
    }
}

public class LessonPlanner : TimeTable
{
    public DateTime LessonDate { get; set; }
}

Upvotes: 2

Views: 124

Answers (1)

Josh Gallagher
Josh Gallagher

Reputation: 5329

Using code first in Entity Framework 5, in the DbContext derived class, override OnModelCreating and add the following code. I've not tried it with your types but I've used a variant of this to create two classes for a three deep hierarchy.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Period>()
                    .Map<Period>(p => p.MapInheritedProperties())
                    .ToTable("Period");

        modelBuilder.Entity<LessonPlanner>()
                    .Map<LessonPlanner>(lp => lp.MapInheritedProperties())
                    .ToTable("LessonPlanner");
    }

Upvotes: 1

Related Questions