首页 > 解决方案 > Overriding classes in an EF Core data access layer

问题描述

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; }
}

标签: c#.net-coreentity-framework-core

解决方案


AppDbContext类应该是可继承的,并且该方法OnModelCreating无论如何都是可覆盖的。在OnModelCreating派生DbContext类的方法中,添加以下代码来定义关系。

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);
}

另外,我Id使用属性在每个类中装饰了[Key]属性。如果不想用[Key]属性装饰,请使用 Fluent 表达式并定义 Id 属性。


推荐阅读