【问题标题】:Entity Framework Model builder with conditioanl foreign key具有条件外键的实体框架模型构建器
【发布时间】:2018-08-29 01:09:04
【问题描述】:

目前我正在研究非常混乱的遗留系统数据库 在酒店预订系统表中,我们有 Reservation 表,它与基于 systemid 的不同预订系统(例如酒店预订、火车预订)具有一对多关系
餐桌 - 预订
列 Reservation_id (int) | System_id(int) |客户 ID|
45432 |可以是 1,2,3 等 | 343 |


例如系统 ID 1 可以是酒店,2 是火车等。

表 - [系统]_预订系统可以是酒店或火车或航班
列 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);

但在初始化时出现以下错误 多重性与 Role 中的引用约束冲突.....因为 Dependent Role 中的所有属性都不可为空,所以 Principal Role 的多重性必须为“1”。

【问题讨论】:

    标签: c# entity-framework entity-framework-6


    【解决方案1】:

    这看起来大致类似于使用 Table-per-Type 的继承模型,但是 System_Id 看起来更像是 Table-per-Hierarchy 的尝试。如果子类表(Hotel_Reservation 等)拥有一个 Reservation ID,那么您应该能够将它映射到 Table-per-Type 并在关系映射中完全忽略 SystemId。本质上,您希望将 Reservation 视为具有扩展它的特定预订类型的基类。从那里您应该能够查询特定的预订类型或基本预订。

    阅读:https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt

    这概述了如何在 EF 中设置关系,以及其他继承数据结构映射,包括 Table-per-Hierarchy。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 2011-02-14
      相关资源
      最近更新 更多