简体   繁体   中英

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

I am upgrading my project from Entity Framework Core 3.1 to Entity Framework Core 6.0, and facing trouble with using enum as a property type for a bigint column of a table built in PostgreSQL.

The error message comes up when I want to select a list of documents from the database by using a column which only contain int , and their string values are defined as enums in the ASP.NET project. The following is an example.

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

In this code snippet, StateEnum is an enumInt in this project.

The error message returning is as follows: 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.

I didn't have this issue when I was just using Entity Framework Core 3.1, so I am very confused how to solve this issue. I also followed this documentation , but it didn't help me either.

You probably need to use Value Conversion .

Your question is not complete, but I assume you have some type

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

SQL can only use integer types for a key, so you'll have to tell it how to convert it manually. eg

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

But IMHO it's better to keep it an int , or long in this case. And do the enum comparison with a casting to int. Strong typed ID is achieved differently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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