簡體   English   中英

使用枚舉獲取實體框架遷移錯誤

[英]Getting Entity Framework migration error with enum

我有一個實體和一個像這樣的枚舉:

public class RequestType
{
    public Guid RequestTypeId { get; set; }
    public RequestActionEnum Name { get; set; }
    public ICollection<Request> Requests { get; set; }
}

這是枚舉RequestActionEnum

public enum RequestActionEnum
{
    New,
    Update,
    Archive
}

我正在使用以下代碼使用 Entity Framework Core 進行數據庫遷移:

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
        modelBuilder.Entity<RequestType>().HasData(
            new RequestType { RequestTypeId = Guid.NewGuid(), Name = RequestActionEnum.New },
            new RequestType { RequestTypeId = Guid.NewGuid(), Name = RequestActionEnum.Update },
            new RequestType { RequestTypeId = Guid.NewGuid(), Name = RequestActionEnum.Archive }
            );
  }

但是在使用Update-Database ,我收到此錯誤:

列“名稱”無法自動轉換為整數類型

我正在使用 Entity Framework Core 3.0 和代碼優先方法,但我不確定為什么會收到此錯誤。

任何人都可以提出有關此問題的任何想法嗎?

提前謝謝了。

EntityFramework 不能很好地處理枚舉值是一個已知問題。 我不知道這是否適用於代碼優先,但我已經成功地將列值映射到枚舉。 在您的實體 (POCO) 中:

[NotMapped]
public RequestActionEnum Name
{
     get { return (RequestActionEnum)NameValue; }
     set { NameValue = (int)value; }
}

[Column("Name")]
public int NameValue { get; set; }

這不是最優雅的解決方案,但它可能會奏效。

我傾向於使用值轉換器將所有枚舉存儲為字符串。 您是否需要明確指定您的枚舉存儲為數字?

暫無
暫無

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

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