【发布时间】:2022-01-12 23:10:35
【问题描述】:
我打算在这里提取男性和女性值的枚举类
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DoB { get; set; }
public enum MF { Male,Female }
public MF Gender { get; set; } //here's my target
}
这里是我从数据库 msql 中提取的数据访问层
public IList<Employee> GetAllEmployees()
{
string query = "EXEC GetAllEmployees";
string constring = "Data Source=.\\SQLEXPRESS;Initial Catalog=ProjectDatabase;Integrated Security=True;Pooling=False";
IList<Employee> AllEmployees = new List<Employee> {};
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
List<Employee> customers = new List<Employee>();
//cmd.CommandType = CommandType.Text;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
AllEmployees.Add(new Employee
{
ID = Convert.ToInt32(sdr["ID"]),
Name = sdr["Name"].ToString(),
DoB = (DateTime)sdr["DoB"],
Gender = (MF)Enum.Parse(typeof(MF), (string)sdr["Gender"]), //here's where it extracts the Gender value as 0 or 1 instead in plain words
});
}
}
con.Close();
return AllEmployees;
}
}
}
业务逻辑层不言自明
public IList<Employee> GetEmployees(string name,MF gender)
{
EmployeeDAL EDAL = new EmployeeDAL();
if (name == "")
return EDAL.GetAllEmployees(); //Ignore this for now
else
return EDAL.GetFilteredEmployees(name,gender); //this gets used in this case
}
一切开始的控制器层
[Route("GetEmployees")]
[HttpPost]
public IList<Employee> GetEmployees(JArray PostData)
{
string Name = (string)PostData[0]["Name"];
MF Gender = (MF)Enum.Parse(typeof(MF), (string)PostData[0]["Gender"]);//grabed from a post request from AngularJS code
EmployeeBLL EBLL = new EmployeeBLL();
return EBLL.GetEmployees(Name,Gender);
}
大家好,我想使用我的 Gender 枚举为 AngularJS POST 请求返回男性或女性,但我一直得到男性 0 和女性 1。我该如何解决? cmets 中的所有其他详细信息。
【问题讨论】:
-
提示:如果您将
enum写入数据库,请将值分配给枚举值。enum MF { Male = 1,Female = 2 }任何添加(可能会)和重新排序都不会破坏向后兼容性。 -
枚举是(当没有其他指定时)一个 int。
Enum.Parse无法返回强类型枚举。 (你可以为它创建一个通用的扩展方法。 -
数据库表中“性别”列的数据类型是什么?
-
如果你有一个
MF,你可以打电话给.ToString。无需铸造。遵循@the2step 所说的内容:var stringValue = MF.Male.ToString(); -
Enum.GetName(typeof(Gender), _value)
标签: c# asp.net angularjs asp.net-mvc-4