表的基本設計
機械M由多個零件C組成
不同的零件有不同的屬性,所以有C1,C2等等
由於零件的差異化,導致C1、C2不能通過統一的表C來表示
同時設計接口InterfaceC作為零件表的接口,整合一些統一的內容
綜上所述,有表M,C1,C2和接口InterfaceC,C1、C2實現InterfaceC
遇到的問題
在M表中,定義
public virtual ICollection<InterfaceC> CList { get; set; }
在C1、C2表中定義
public int MId { get; set; }
public virtual M M { get; set; }
在M中配置
modelBuilder.Entity<M>().HasMany(x => x.CList)
.WithOne(x => x.M)
.HasForeignKey(x => x.MId);
報錯:
The specified type 'InterfaceC'must be a non-interface reference type to be used as an entity type .
即ef core不能接受接口引用類型作為實體類型
解決方式
在M表中定義兩個集合, 兩個集合對應C1、C2表的兩個外鍵
public virtual ICollection<C1> C1List { get; set; }
public virtual ICollection<C2> C2List { get; set; }
在C1、C2中分別配置
modelBuilder.Entity<C1>().HasOne(x => x.M)
.WithMany(x => x.C1List)
.HasForeignKey(x => x.MId);
modelBuilder.Entity<C2>().HasOne(x => x.M)
.WithMany(x => x.C2List)
.HasForeignKey(x => x.MId);
就ok啦
題外話
當然這種數據結構還是推薦使用nosql,mongo的方式
這里只是剛好討論到ef core~