EF Core 建立一對一關係
阿新 • • 發佈:2022-05-25
1 public class Sys_Menu : IEntity 2 { 3 4 /// <summary> 5 /// Id 6 /// </summary> 7 [Key] 8 public int Id { get; set; } 9 10 /// <summary> 11 /// Path 12 /// </summary> 13 public String Path { get; set; } 14 15 /// <summary> 16 /// 名稱 17 ///</summary> 18 public String Name { get; set; } 19 /// <summary> 20 /// Component 21 /// </summary> 22 public String Component { get; set; } 23 /// <summary> 24 /// Redirect 25 /// </summary> 26 public String Redirect { get; set; } 27 28 /// <summary>29 /// 啟用/禁用 30 /// </summary> 31 public Enable IsEnable { get; set; } 32 33 /// <summary> 34 /// 排序 35 /// </summary> 36 public int Sort { get; set; } 37 38 /// <summary> 39 /// 父級 40 /// </summary> 41 public int? PID { get; set; } 42 43 [NotMapped]44 public List<Sys_Menu> Children { get; set; } 45 46 public Sys_Meta Meta { get; set; } 47 }
1 public class Sys_Meta : IEntity 2 { 3 /// <summary> 4 /// Id 5 /// </summary> 6 [Key] 7 public int MetaId { get; set; } 8 9 /// <summary> 10 /// 選單名稱 11 /// </summary> 12 public String Title { get; set; } 13 14 /// <summary> 15 /// 開啟外鏈條件,`1、isLink: true 2、連結地址不為空(meta.isLink) 3、isIframe: false` 16 /// </summary> 17 public String IsLink { get; set; } 18 19 /// <summary> 20 /// 選單是否隱藏(選單不顯示在介面,但可以進行跳轉) 21 /// </summary> 22 public bool IsHide { get; set; } 23 24 /// <summary> 25 /// 選單是否快取 26 /// </summary> 27 public bool IsKeepAlive { get; set; } 28 /// <summary> 29 /// 選單是否固定(固定在 tagsView 中,不可進行關閉),右鍵選單無 `關閉` 項 30 /// </summary> 31 public bool IsAffix { get; set; } 32 33 /// <summary> 34 /// 開啟條件,`1、isIframe: true 2、連結地址不為空(meta.isLink)` 35 /// </summary> 36 public bool IsIframe { get; set; } 37 38 /// <summary> 39 /// 許可權標識 40 /// </summary> 41 public String[] Roles { get; set; } 42 /// <summary> 43 /// 選單圖示 44 /// </summary> 45 public String Icon { get; set; } 46 47 /// <summary> 48 /// 選單Id 49 /// </summary> 50 public int Id { get; set; } 51 52 53 }
現有以上兩個model,Sys_Menu 和 Sys_Meta,兩者為一對一關係 即一個 Sys_Menu 對應一個 Sys_Meta
注意已設定 Sys_Menu 中對應的 Sys_Meta
即:
public Sys_Meta Meta { get; set; }
現在到 Sys_Menu 的 Configure 中去配置 對應關係
public class Sys_MenuConfigure : IEntityTypeBuilder<Sys_Menu> { public void Configure(EntityTypeBuilder<Sys_Menu> entityBuilder, DbContext dbContext, Type dbContextLocator) { entityBuilder .HasOne(b => b.Meta) .WithOne() .HasForeignKey<Sys_Meta>(b => b.Id); } }
執行 查詢
// 查詢所有Menu 序列化儲存 var DbMenu = await _personRepository.AsQueryable().OrderByDescending(x => x.Sort) .Include(x => x.Meta).ToListAsync();
查詢 結果如下