c# - 如何在 EF6 中对不同实体使用同一张表
问题描述
我有具有导航属性的实体 DbDropPhoto
public class DbDropPhoto
{
public virtual DbContour Contour { get; set; }
}
public class DbContour
{
public virtual DbDropPhoto CurrentDropPhoto { get; set; }
}
使用 FluentAPI 像这样配置关系:
modelBuilder.Entity<DbContour>()
.HasRequired(s => s.CurrentDropPhoto)
.WithOptional(s => s.Contour)
.WillCascadeOnDelete();
现在我需要将相同的 DbContour 实体添加到另一个名为 DbThermalPhoto 的实体中。最好的方法是什么。我应该创建单独的表,例如 DbThermalPhotoContour,还是可以以某种方式重新使用现有表。我已经搜索过类似的问题,但它们的解决方案似乎非常复杂。
解决方案
我设法像这样实现它:
modelBuilder.Entity<DbDropPhoto>()
.HasOptional(c => c.Contour)
.WithMany()
.HasForeignKey(s => s.ContourId);
modelBuilder.Entity<DbThermalPhoto>()
.HasOptional(c => c.Contour)
.WithMany()
.HasForeignKey(s => s.ContourId);
和实体:
[Table("DropPhotos")]
public class DbDropPhoto
{
[Key] public Guid PhotoId { get; set; }
public Guid? ContourId { get; set; }
[ForeignKey("ContourId")]
public virtual DbContour Contour { get; set; }
}
[Table("ThermalPhotos")]
public class DbThermalPhoto
{
[Key] public Guid PhotoId { get; set; }
public Guid? ContourId { get; set; }
[ForeignKey("ContourId")]
public virtual DbContour Contour { get; set; }
}
推荐阅读
- automation - 从支持导入文件以用于集成测试用例的问题
- ios - Snapkit - right.width.center 和 right, width, center 有区别吗?
- css - 尝试导入错误:“createGlobalStyle”未从“样式组件”导出
- django - 如何修复“M”值必须为 True 或 False
- python - 请求标头中的签名密钥
- react-native - React Navigation,是否有一种简单的方法覆盖 onClick 抽屉导航器,或返回堆栈顶部?
- matplotlib - Jupyter 没有显示正确的 matplotlib 图和 seaborn 图
- firebase-realtime-database - 更新 Post (Firebase) 中的点赞数
- battery - 我们可以使用 pvlib 逆变器功能为电池存储系统的 DC-DC 转换器建模吗?
- google-cloud-firestore - Cloud Firestore 函数触发器和事务 - 如何正确返回承诺