【问题标题】:Getting Entity Framework migration error with enum使用枚举获取实体框架迁移错误
【发布时间】:2020-03-29 20:02:57
【问题描述】:

我有一个这样的实体和一个枚举:

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 和代码优先方法,但我不确定为什么会收到此错误。

有人可以就这个问题提出任何想法吗?

非常感谢。

【问题讨论】:

  • 您的数据库中Name 列的数据类型是什么?
  • 它是枚举,我使用它来创建数据库和代码优先方法

标签: c# .net entity-framework entity-framework-core entity-framework-migrations


【解决方案1】:

EntityFramework 不能很好地处理枚举值是一个已知问题。我不知道这适用于代码优先,但我已经成功地将列值映射到具有类似这样的枚举。在您的实体 (POCO) 中:

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

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

这不是最优雅的解决方案,但它可能会起作用。

【讨论】:

    【解决方案2】:

    我倾向于使用value converter 将所有枚举存储为字符串。您是否需要明确指定您的枚举存储为数字?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      相关资源
      最近更新 更多