c# - 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; }
}
解决方案
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 属性。
推荐阅读
- amazon-redshift - 无法使用 Epoch 日期转换为红移日期创建自动刷新视图
- c - 警告:导入 unistd.h 后函数“sbrk”的隐式声明
- azure - Azure API 提取
策略的响应状态码 - apache-kafka - Kafka 使用 Confluent Playbooks 从 5.4.1 升级到 6.1.2
- c# - 如何使用 .net core 删除 pfx 证书
- linux - Bash 计算循环中文件和行的总数
- python-3.x - 如何在 Pywinauto 中移动和调整 UIAWrapper 而不将焦点放在被移动的窗口上
- javascript - NodeJS如何让我的路由脱离中间件
- c++ - 从 std::vector 转换为 std::array
- php - Slim 4 捕捉 php 警告、通知和错误