【问题标题】:How to use enum in Visual C# ASP .NET MVC 4 Web Application如何在 Visual C# ASP .NET MVC 4 Web 应用程序中使用枚举
【发布时间】:2023-04-11 10:40:01
【问题描述】:

如何在 Visual C# ASP .NET MVC 4 Web 应用程序中使用枚举?

我有一个 mySQL 数据库,其中包含一个表“flight”,其中包含一个使用该类型的字段“flightDay” enum('星期一', '星期二', '星期三', '星期四', utf8_bin

如何使表 Flight 的类编译/工作?在我的应用程序的模型文件中。

[Table("flight")]
public class Flight
{
    [Key,  Column(Order = 1)]
    public int id { get; set; }
    public int route { get; set; }
    public enum  flightDay { get; set; } **// How to make this work?**
    public int aircraft { get; set; }

}

【问题讨论】:

  • 当你从数据库中检索它时,你必须将它从字符串转换为枚举类型
  • @Dan Hunex 请你解释一下怎么做?

标签: c# mysql enums


【解决方案1】:

将它们存储为整数 id。可选择作为 Days 表的外键作为代码表,以支持 SQL 查找。

public enum Day { Monday = 1, Tuesday =2, ... }

[Table("flight")]
public class Flight
{
    [Key,  Column(Order = 1)]
    public int id { get; set; }
    public int route { get; set; }
    public int flightDayId { get; set; } 

    // Provides enum abstraction for flightDayId
    public Day FlightDay { 
      get { return (Day)flightDayId; } 
      set { flightDayId = (int)value; }
    }
    public int aircraft { get; set; }

}

【讨论】:

    【解决方案2】:

    sql 中没有枚举对应的数据类型。因此,您必须将其作为字符串带入 c# 代码并将其 ( Enum.TryParse ) 转换为相应的枚举。所以你不能让数据库实体有枚举属性,把它改成stirng

        string FlightDay{get;set;}
    

    这是一个例子

    public class Flight
    {
        [Key,  Column(Order = 1)]
        public int id { get; set; }
        public int route { get; set; }
        public String  flightDay { get; set; } 
        public int aircraft { get; set; }
    
        [NotMapped]
        public FlightDays FlightDayEnum
        {
            get
            {
                FlightDays day;
                Enum.TryParse<FlightDays>(flightDay, out day);
                return day;
            }
        }
    
       }
    
        public enum FlightDays
        {
            Monday,
            Tuesday,
            Wendsday,
            Thursday,
            Friday,
            Saturday,
            Sunday
         }
    

    在 DB 中,您应该将航班日期拼写与枚举完全相同。

    在上面的示例中,“FlightDayEnum”没有映射到数据库,而是作为字符串和枚举之间的转换器。

    【讨论】:

    • 这会在 set 方法中吗?获取方法?你能给我举个一天的例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多