Overriding classes in an EF Core data access layer

.net-core c# entity-framework-core

Question

My company has a core database schema that's shared between all of our customers, and we then have customer-specific schemas for each customer. The core DB itself never changes. We're looking to make a NuGet package for the core data access project, then have our customer-specific projects just extend from that one.

I have everything set up to inherit from the core project and that works correctly. My problem now is that we need to add a navigation property to one of the core classes. The table is exactly the same, but we've added a customer-specific table with a FK to this core table and thus need a navigation property. Is it possible to do this, essentially override the core class with the customer-specific one?

As an example, here's a core class:

public class Shape
{
    public int Id { get; set; }
    public string Name { get; set; }
}

A customer now wants to add colors that each shape can have:

public class ShapeColor
{
    public int Id { get; set; }
    public string HexCode { get; set; }
    public int ShapeId { get; set; }

    public Shape Shape { get; set; }
}

The core class hasn't changed in the DB, but we need a navigation property to be able to configure it for EF Core:

public class Shape
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<ShapeColor> Colors { get; set; }
}
1
4
8/15/2018 1:06:01 PM

Popular Answer

AppDbContext class should be inheritable and the method OnModelCreating is anyhow overridable. In the OnModelCreating method of derived DbContext class, add the following code to define the relationship.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // modelBuilder.Entity<Shape>().HasKey(x=>x.Id);

    modelBuilder.Entity<ShapeColor>(x =>
    {
        // x.HasKey(p => p.Id);
        x.Property(p => p.ShapeId).IsRequired();
        x.HasOne<Shape>().WithMany().HasForeignKey(y => y.ShapeId);
    });
    base.OnModelCreating(modelBuilder);
}

Also, I have decorated Id property in each class using [Key] attribute. If you don't want to decorate with [Key] attribute, use Fluent expression and define Id properties.

3
8/15/2018 2:06:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow