Something similar along the lines of your requirement is possible by using Table per Concrete Type inheritance model.
Entities
public abstract class BaseEntity {
public int RecordID { get; set; }
public abstract int ProjectType { get; }
public string Title { get; set; }
}
public class Project1Entity : BaseEntity {
public override int ProjectType {
get { return 1; }
}
public string Project1Field { get; set; }
}
public class Project2Entity : BaseEntity {
public override int ProjectType {
get { return 2; }
}
public string Project2Field { get; set; }
}
DBContext
public class DataContext : DbContext {
public DbSet<Project1Entity> Project1Entities { get; set; }
public DbSet<Project2Entity> Project2Entities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<BaseEntity>().HasKey(o => o.RecordID);
modelBuilder.Entity<Project1Entity>().Map(m => {
m.MapInheritedProperties();
m.ToTable("project_1_table");
});
modelBuilder.Entity<Project2Entity>().Map(m => {
m.MapInheritedProperties();
m.ToTable("project_2_table");
});
}
}
However there are several limitations
- with this configuration EF isn't able to generate the
RecordID
for new records, so you have to provide value of the primary key yourself - it will work only if
RecordID
for items in project_1_table and project_2_table doesn't collide. If they do, you need to specify another primary key - e.g. add columnProjectType
to the database and use the composite primary key{RecordID, ProjectType}
Version with composite key
Entities
public abstract class BaseEntity {
public int RecordID { get; set; }
public int ProjectType { get; set; }
public string Title { get; set; }
}
public class Project1Entity : BaseEntity {
public string Project1Field { get; set; }
}
public class Project2Entity : BaseEntity {
public string Project2Field { get; set; }
}
DBContext
public class DataContext : DbContext {
...
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
...
modelBuilder.Entity<BaseEntity>().HasKey(o => new { o.RecordID, o.ProjectType });
...
}
}