簡體   English   中英

將多個實體映射到單個表

[英]Mapping multiple Entities to a single table

我有以下(示例)實體:

public abstract class Vehicle<TVehicleDetails> where TVehicleDetails : VehicleDetails
{
    public int VehicleId { get; set; }
    public TVehicleDetails? Details { get; set; }
}
public class Car : Vehicle<CarDetails> { }
public class Truck : Vehicle<TruckDetails> { }

我能夠 map 實體CarTruck ,沒有任何問題:

modelBuilder.Entity<Car>().OwnsOne(p => p.Details).WithOwner();
modelBuilder.Entity<Truck>().OwnsOne(p => p.Details).WithOwner();

我還有以下(示例)實體:

public class PromotionVehicle<TVehicle, TVehicleDetails>
    where TVehicle : Vehicle<TVehicleDetails>
    where TVehicleDetails : VehicleDetails
{
    public int PromotionVehicleId { get; set; }
    public TVehicle { get; set; }
    public int VehicleId { get; set; }
    public VehicleType VehicleType { get; set; } // this is just an enum
}

這就是我嘗試 map PromotionVehicle<Car, CarDetails>PromotionVehicle<Truck, TruckDetail>到同一張表但無濟於事的方式:

modelBuilder.Entity<PromotionVehicle<Car, CarDetails>>().ToTable("PromotionVehicles");
modelBuilder.Entity<PromotionVehicle<Truck, TruckDetails>>().ToTable("PromotionVehicles");
modelBuilder.Entity<PromotionVehicle<Vehicle<VehicleDetails>, VehicleDetails>>>().ToTable("PromotionVehicles").HasDiscriminator(p => p.VehicleType).HasValue<PromotionVehicle<Car, CarDetails>>(VehicleType.Car).HasValue<PromotionVehicle<Truck, TruckDetails>>(VehicleType.Truck);

但是,當嘗試創建Migrations時,可以理解的是,EntityFramework 會拋出一個Exception ,並顯示一條錯誤消息PromotionVehicle<Car, CarDetails> is not a descendent of PromotionVehicle<Vehicle<VehicleDetails>, VehicleDetails>>

實際上,我想做的是告訴 EntityFramework,當它查看“PromotionVehicles”表時, VehicleType列應該告訴它要查看哪個“車輛表”,然后加載適當的Vehicle<>實體(使用IQueryable<>.Include ). 我相信那里有必要的信息位告訴 EntityFramework 去哪里VehicleType決定是看“Cars”還是“Trucks”, VehicleId滿足ForeignKey要求。

這種配置完全可能嗎?

在我看來,您的PromotionVehicle是一個鏈接其他表(關系表)的表

如果這是正確的,您可以只存儲相關表的 ID,使用 EF 存儲和檢索這些 ID,然后使用這些 ID 在自定義“LoadPromotionVehicle”方法中加載每個實體

這是一些偽代碼

public class PromotionVehicleRelations
{
    public int PromotionVehicleId { get; set; }
    public Int VehicleId { get; set; } //store just IDs not entity
    public int VehicleDetailsID { get; set; } //store just IDs not entity
    public VehicleType VehicleType { get; set; } // enums
}

PromotionVehicle pv ;
PromotionVehicleRelations pvr ;
PromotionVehicleId pvID = 1234 ;

//load the table with the IDs using regular EF mapping
pvr = EF.load(pvID) ;

//populate a new entity with full details that you need using the IDs
pv = LoadPromotionVehicle(pvr) ;

LoadPromotionVehicle(PromotionVehicleRelations pvr) {
  pv.TVehicle = EF.loadVehicle(pvr.VehicleId)
  pv.VehicleDetails = EF.loadVehicleDetails(pvr.VehicleDetailsID) ;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM