I have a Inheritance Hierarchy where Action is parent of ActionCompleted and ActionCancelled. Order class has a zero to one ActionCompleted and ActionCancelled. I have tried TPH and TPT (even tried edmx) but unable to get Entity to understand this relationship between Order and child actions, please suggest how do I map?
//Classes
public class Order
{
public int OrderId { get; set; }
public string Name { get; set; }
public ActionCompleted ACO { get; set; }
public ActionCancelled ACA { get; set; }
}
public class Action
{
public int ActionID { get; set; }
public DateTime ActionDT { get; set; }
public Order Order { get; set; }
}
public class ActionCompleted : Action
{
}
public class ActionCancelled : Action
{
public int CancelledByPhysician { get; set; }
}
//Mappings
public class EDISContext:DbContext
{
public EDISContext()
: base("EDISContext")
{ }
public DbSet<Order> Orders { get; set; }
public DbSet<Action> Actions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().ToTable("Orders");
modelBuilder.Entity<Action>().HasKey(a => a.ActionID);
modelBuilder.Entity<Action>().Map(m => m.ToTable("Actions"))
.Map<ActionCompleted>(m => m.ToTable("ActionCompleted"))
.Map<ActionCancelled>(m => m.ToTable("ActionCancelled"));
//modelBuilder.Entity<Action>().HasRequired(a => a.Order).WithOptional().Map(m => m.MapKey("DiagOrderId"));
modelBuilder.Entity<ActionCompleted>().HasRequired(a => a.Order).WithOptional().Map(m => m.MapKey("DiagOrderId"));
modelBuilder.Entity<ActionCancelled>().HasRequired(a => a.Order).WithOptional().Map(m => m.MapKey("DiagOrderId"));
}
}
Code used to save data:
EDISContext db = new EDISContext();
var ord1 = db.Orders.FirstOrDefault(o => o.OrderId == 1);
ActionCompleted ac= new ActionCompleted();
ac.ActionDT = DateTime.Now;
ac.Order = ord1;
db.Actions.Add(ac);
db.SaveChanges();
Script of DB tables:
CREATE TABLE [dbo].[Orders](
[OrderId] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[Actions](
[ActionID] [int] IDENTITY(1,1) NOT NULL,
[ActionDT] [datetime] NOT NULL,
[DiagOrderID] [int] NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[ActionCompleted](
[ACID] [int] IDENTITY(1,1) NOT NULL,
[ActionID] [int] NOT NULL,
) ON [PRIMARY]
CREATE TABLE [dbo].[ActionCancelled](
[ACAID] [int] IDENTITY(1,1) NOT NULL,
[ActionID] [int] NOT NULL,
[CancelledByPhysician] [int] NULL,
) ON [PRIMARY]