首页 > 解决方案 > 具有条件外键的实体框架模型构建器

问题描述

目前我正在研究非常混乱的遗留系统数据库在酒店预订系统表中,我们有预订表,它与基于 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”。

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

解决方案


这看起来大致像使用 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。


推荐阅读