[已解决]如何在jsonResult中将性别检索为字符串,例如“ gender”:“ Male”,我正在将EntityFramework Core 2.2与Asp.net core 2.2项目结合使用。我在枚举中遇到麻烦,但是在此示例中,枚举返回字符串而不是int (https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-types/enums)
我的模范雇员
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime Birthdate { get; set; }
public Genders Gender { get; set; }
}
我的员工配置
public void Configure(EntityTypeBuilder<Employee> builder)
{
builder.ToTable("Employee", "HR");
builder.Property(e => e.Id)
.ValueGeneratedOnAdd();
builder.Property(e => e.FirstName)
.IsRequired()
.HasMaxLength(50);
builder.Property(e => e.MiddleName)
.IsRequired()
.HasMaxLength(50);
builder.Property(e => e.LastName)
.IsRequired()
.HasMaxLength(50);
builder.Property(e => e.Birthdate)
.HasColumnType("Date");
builder.Property(e => e.Gender)
.HasConversion(
g => g.ToString(),
g => (Genders)Enum.Parse(typeof(Genders), g));
}
我的枚举性别
public enum Genders
{
Unknown,
Male,
Female
}
我的存储库
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly DbContext Context;
private readonly DbSet<TEntity> _entities;
public Repository(DbContext context)
{
Context = context;
_entities = Context.Set<TEntity>();
}
public async Task<IEnumerable<TEntity>> ToListAsync()
{
return await _entities.ToListAsync();
}
}
我的API控制器
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IEnumerable<Employee>> Get()
{
return await _employees.ToListAsync();
}
我的结果
[
{
"id": 2,
"firstName": "First Name 1",
"middleName": "Middle Name 1",
"lastName": "Last Name 1",
"birthdate": "1991-10-04T00:00:00",
"gender": 1 // I Want this result "gender": "Male"
}
]
解决方案:我将此添加到我的startup.cs
.AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
});