I have the class
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? DeactivatedOn { get; set; }
public DateTime? UpdatedOn { get; set; }
public bool IsActive { get; set; }
}
public class Supplier : Company
{
public int ContactId { get; set; }
public int DocumentId { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
}
These are the mappings
public class CompanyMap : EntityTypeConfiguration<Company>
{
public CompanyMap()
{
// Primary Key
HasKey(c => c.Id);
//Table
ToTable("Company");
}
}
public class SupplierMap : EntityTypeConfiguration<Supplier>
{
public SupplierMap()
{
// Primary Key
HasKey(s => s.Id);
// Properties
//Relationship
HasRequired(s => s.Company)
.WithMany().HasForeignKey(c => c.CompanyId);
//Table
ToTable("Supplier");
}
}
This is the context
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new CompanyMap());
modelBuilder.Configurations.Add(new SupplierMap());
}
public DbSet<Company> Companies { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
}
Seeding:
var companies = new List<Company>
{
new Company {Id = 1, Name = "X", CreatedOn = DateTime.Now, IsActive = true, UpdatedOn = DateTime.Now},
new Company {Id = 2, Name = "XX", CreatedOn = DateTime.Now, IsActive = true, UpdatedOn = DateTime.Now},
new Company {Id = 3, Name = "XXX", CreatedOn = DateTime.Now, IsActive = true, UpdatedOn = DateTime.Now},
new Company {Id = 4, Name = "XXXX", CreatedOn = DateTime.Now, IsActive = true, UpdatedOn = DateTime.Now},
};
foreach (var item in companies)
{
context.Companies.AddOrUpdate(item);
}
var suppliers = new List<Supplier>
{
new Supplier {Id = 1, CreatedOn = DateTime.Now, Company = companies[0], IsActive = true, UpdatedOn = DateTime.Now},
new Supplier {Id = 2, CreatedOn = DateTime.Now, Company = companies[1], IsActive = true, UpdatedOn = DateTime.Now},
new Supplier {Id = 3, CreatedOn = DateTime.Now, Company = companies[2], IsActive = true, UpdatedOn = DateTime.Now},
new Supplier {Id = 4, CreatedOn = DateTime.Now, Company = companies[3], IsActive = true, UpdatedOn = DateTime.Now}
};
foreach (var item in suppliers)
{
context.Suppliers.AddOrUpdate(item);
}
this.SaveChanges(context);
What I am expecting is 2 tables with all inherited with same properties, (base class and inherited class but I cant this to work, my result is a single table with a [Discriminator] collunn.
Any help is more than welcome.
Regards