2

I have below model structure in EF core Code first approach.

public abstract class  BaseModel
{
    [Key]
    public string Id { get; set; }
    public DateTime LastUpdatedDate { get; set; }
}


public class Company  :BaseModel
{
     
    public string Name { get; set; }
    public string Address { get; set; }
}

public class CompanyLog :Company
{
     
    public string LogId { get; set; }
    public DateTime LogDate { get; set; }
}

and DB Context is
public class MyDbContext : DbContext
{
     public DbSet<Company> Company { get; set; }
     public DbSet<CompanyLog> CompanyLog { get; set; }
}

But after DB migration, CompanyLog table is getting created with only its own properties, but not with base table properties. How can I acheive this? After the db migration, database table structure expectation is

CREATE TABLE dbo."Company"
(
    Id text  NOT NULL,
    LastUpdatedDate TimeStamp, 
    Name text, 
    Address text, 
)
CREATE TABLE dbo."CompanyLog"
(
    Id text  NOT NULL,
    LastUpdatedDate TimeStamp, 
    Name text, 
    Address text, 
    LogId text   NULL,
    LogDate TimeStamp,  
)

1 Answer 1

2

CompanyLog table is getting created with only its own properties, but not with base table properties

It's because EF Core considers Company and CompanyLog being a part of a database inheritance, hence implements one of the supported strategies for that (currently TPH (Table-per-hierarchy) and starting from EF Core 5.0, TPT (Table-per-type)).

In fact the way it is shown in the post (i.e. without additional data annotations and/or fluent configuration) I'm getting a single table with disciminator column, which is the implementation of TPH. Probably you have something additional which gives you TPT - two tables, the "base" holding the base properties and "derived" holding just the additional properties.

What you need is either TPC (Table-per-class) or no database inheritance at all. The former is not supported yet, and the later can be achieved with the following fluent configuration (no data annotation exist so far):

modelBuilder.Entity<CompanyLog>().HasBaseType((Type)null);
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. I have disabled the database inheritence by using modelBuilder.Entity<CompanyLog>().HasBaseType((Type)null); And it is working fine. Thanks...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.