# EF Core enum 數值轉換 ###### tags: `C#` `EFCore` ## 學習目標 使EF enum類別儲存時轉換為字串對應方式,使資料庫查詢方便檢視。 ## 目錄 [TOC] # 預設資料 要說明之前我們先預設實體類別的定義 > 以下範例資料庫對象為MySql ```csharp= [Table("game_platform")] public class GamePlatform { [Key] [Column("id")] public int Id { get; set; } [Column("platform")] public PlatformType Platform { get; set; } } ``` 其列舉如下 ```csharp= public enum PlatformType { Steam, Ubisoft, Epic, GOG } ``` # 轉換說明 我們希望列舉儲存後不在是數值方式存放而是字串(ex.Ubisoft、Steam),這邊我們選擇在`OnModelCreating`中設定好我們想要轉換 ```csharp= protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<GamePlatform>() .Property(x => x.Platform) .HasConversion( new EnumToStringConverter<PlatformType>() ); } ``` 設定完成即可在儲存/撈取時自動轉換成對應的字串/列舉,前往資料庫查詢資料時也就不會是顯示0、1、2......這類的數字。 # 結論 這邊只是單純紀錄有再專案上使用的方式,其轉換做法還有種有興趣的人可至參考連結查看。 <br/> --- 相關參考來源: [Microsoft](https://docs.microsoft.com/zh-tw/ef/core/modeling/value-conversions?tabs=data-annotations#configuring-a-value-converter) <style> code > span{ color: red;} </style>