简体   繁体   中英

EF Core MySql does not show enum values

In my project I am using asp.net core 2.2 and mysql for db. Before when I selected enum values (before used postgre) it showed exact values for me, but now it shows integers instead of values.

My startup connection:

 services.AddDbContext<AppDbContext>(x => 
     x.UseMySql(Configuration.GetConnectionString("LibvirtConnection"))
                .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));

My select stament:

 [HttpGet]
 public IActionResult GetVMs()
    {
        var model =
            from vm in _context.VirtualMachines
            join project in _context.Projects on vm.ProjectId equals project.Id
            join hypervisor in _context.Hypervisors on vm.HypervisorId equals 
             hypervisor.HypervisorId
            join managment in _context.Managements on vm.ManagementId equals managment.Id
            select new
            {
                Id = vm.Id,
                Name = vm.Name,
                IpAddress = vm.IpAddress,
                DiskSize = vm.DiskSize,
                Cpu = vm.CPU,
                Ram = vm.Ram,
                ImageUrl = vm.ImageUrl,
                Role = vm.Role.ToString(),
                Status = vm.Status.ToString(),
                Project = project.Name,
                Hypervisor = hypervisor.Name,
                Gateway = managment.Gateway,
                Netmask = managment.Netmask
            };
        return Ok(model);
    }

I got result back:

{
    "id": 1,
    "name": "kubernetesvm",
    "ipAddress": "185.22.98.7",
    "diskSize": 500,
    "cpu": 24,
    "ram": 500,
    "imageUrl": "https://www.google.com",
    "role": "1",
    "status": "0",
    "project": "avengers",
    "hypervisor": "kubernetes",
    "gateway": "vh10",
    "netmask": 24
}

It should be actual values for role and status.

The problem is that ToString() on the Enum uses the default format specifier "D" , which prints the number behind the Enum value, but when specifying the format manually to be "G" the ToString("G") method returns the name as it is written in source, so that should fix your problem, replace .ToString() with .ToString("G")

So:

Role = vm.Role.ToString("G"),
Status = vm.Status.ToString("G")

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