繁体   English   中英

如何在 EF Core 6.0 中使用“枚举”作为属性类型

[英]How to use `enum` as a property type in EF Core 6.0

我正在将我的项目从 Entity Framework Core 3.1 升级到 Entity Framework Core 6.0,并且在使用enum作为 PostgreSQL 中构建的表的bigint列的属性类型时遇到了麻烦。

当我想 select 使用仅包含int的列从数据库中获取文档列表时出现错误消息,并且它们的字符串值在 ASP.NET 项目中定义为枚举。 下面是一个例子。

List<Document> documents = DbContext.Documenets.Where(x => x.StateId == StateEnum.Checked).ToList();

在这个代码片段中, StateEnum是这个项目中的一个enumInt

返回的错误消息如下: Identity value generation cannot be used for the property 'Id' on entity type 'State' because the property type is 'StateEnum'. Identity columns can only be of type short, int or long. Identity value generation cannot be used for the property 'Id' on entity type 'State' because the property type is 'StateEnum'. Identity columns can only be of type short, int or long.

我刚使用Entity Framework Core 3.1时没有这个问题,所以我很困惑如何解决这个问题。 我也遵循了这个文档,但它也没有帮助我。

您可能需要使用Value Conversion

您的问题不完整,但我假设您有某种类型

public class State{
...
    StateEnum Id;
...
}

SQL 只能使用 integer 类型作为密钥,因此您必须告诉它如何手动转换。 例如

public class State {
...
    [Column(TypeName = "bigint")]
    StateEnum Id;
...
}

但是恕我直言,在这种情况下最好将其保留为intlong 并通过转换为 int 进行枚举比较。 强类型 ID 的实现方式不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM