简体   繁体   English

EF Core MySql 不显示枚举值

[英]EF Core MySql does not show enum values

In my project I am using asp.net core 2.2 and mysql for db.在我的项目中,我使用 asp.net core 2.2 和 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.在我选择枚举值之前(在使用 postgre 之前)它为我显示了确切的值,但现在它显示的是整数而不是值。

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")问题是 Enum 上的ToString()使用默认格式说明符"D" ,它打印 Enum 值后面的数字,但是当手动指定格式为"G"ToString("G")方法返回名称因为它是在源代码中编写的,因此应该可以解决您的问题,请将.ToString()替换为.ToString("G")

So:所以:

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

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

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