c# - 具有条件外键的实体框架模型构建器
问题描述
目前我正在研究非常混乱的遗留系统数据库在酒店预订系统表中,我们有预订表,它与基于 systemid
表的不同预订系统(例如酒店预订、火车预订)具有一对多关系 - 预订
列 Reservation_id (int) | System_id(int) | 客户ID|
45432 | 可以是 1,2,3 等 | 第343章
例如系统 id 1 可以是酒店,2 是火车等。
Table - [System]_Reservation 系统可以是酒店或火车或航班
Column Reservation_id (int) | create_date(datetime) |其他列 45432 |
目前要加载预订详细信息,我们查询预订表而不是根据系统 ID 我们查询相应的预订系统表。每个预订可以与预订系统有 0..1* 对多的关系。我如何围绕此创建 EF mdel 构建器。我尝试了以下
[Table("Hotel_Reservation")]
public class HotelReservation
{
public int Reservation_id { get; set; }
public Virtual Reservation ReservationInfo { get; set; }
//other properties etc
}
[Table("Reservation")]
public class Reservation
{
public Reservation()
{
HotelReservations = new HashSet<HotelReservation>();
TrainReservations = new HashSet<TrainReservation>();
}
public int Reservation_id { get; set; }
public int SystemID { get; set; }
public virtual ICollection<HotelReservation> HotelReservations { get; set; }
public virtual ICollection<TrainReservation> TrainReservations { get; set; }
//other properties etc
}
//On model builder class contains
Builder.Entity<TrainReservation>()
.HasOptional(x => x.ReservationInfo)
.WithMany(x => x.TrainReservations )
.HasForeignKey(x => x.Reservation_id);
但是在初始化时出现以下错误多重性与角色中的引用约束冲突.....因为从属角色中的所有属性都是不可为空的,所以主体角色的多重性必须为“1”。
解决方案
这看起来大致像使用 Table-per-Type 的继承模型,但是 System_Id 看起来更像是 Table-per-Hierarchy 的尝试。如果子类表(Hotel_Reservation 等)拥有一个 Reservation ID,那么您应该能够将它映射到 Table-per-Type 并在关系映射中完全忽略 SystemId。本质上,您希望将 Reservation 视为具有扩展它的特定预订类型的基类。从那里您应该能够查询特定的预订类型或基本预订。
这概述了如何在 EF 中设置关系,以及其他继承数据结构映射,包括 Table-per-Hierarchy。
推荐阅读
- android - 在mysql上用时间更新recyclerview
- excel - 如果该行中的单元格已被有条件地格式化,则突出显示单元格或行
- mysql - MySQL 用户定义函数 - SQL 语法错误
- python - linux中的“python -c'print'”和“(python -c'print'; cat)”有什么区别
- frames - 从视频中提取帧时如何避免视频中重复或相似的帧?
- javascript - 将更改的 HTML 保存到 Javascript 变量?
- actionscript-3 - AS3:如何检测负数
- python-3.x - 将 csv 列表导出为垂直(列)
- ruby - Ruby:在外部模块中调用时未定义 attr_accessor 方法
- swift - NSUserDefaultsController:“尝试将非属性列表对象...设置为键的 NSUserDefaults/CFPreferences 值...”