【发布时间】:2017-07-07 10:18:01
【问题描述】:
我正在尝试将 JSON 对象发布到我的服务,对其进行反序列化并将其保存到数据库中。它有效——有点。问题是 JSON 的某些字段被保存到数据库中,而其他字段为空。
例如,发布此 JSON 时:
{
"FirstName": "Michael",
"LastName": "Ledley",
"BirthPlace": "Austria",
"Gender": "M",
"OIB": "12348879991",
"CurrentPlace": "New Guinea",
"Department": "D_21570"
}
...在数据库中只有CurrentPlace、Gender和Department被正确存储,而所有其他值(FirstName、LastName、BirthPlace、...)为NULL。它们的类型都是VARCHAR(45),与正确存储的CurrentPlace相同。
执行保存的代码如下所示:
[RoutePrefix("api/employee")]
public class EmployeeApiController : ApiController
{
readonly EmployeePersistence persistence;
public EmployeeApiController()
{
persistence = new EmployeePersistence();
}
[HttpPost]
[Route("")]
public void Post([FromBody] Employee employee)
{
// saving id for the debugging purposes
long id = persistence.SaveEmployee(employee);
}
public long SaveEmployee(Employee employee)
{
string sqlString =
"INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) " +
"VALUES (@FirstName, @LastName, @BirthPlace, @CurrentPlace, @Gender, @Department, @OIB)";
MySqlCommand cmd = new MySqlCommand(sqlString, conn);
cmd.Parameters.AddWithValue("@FirstName", employee.FirstName);
cmd.Parameters.AddWithValue("@LastName", employee.LastName);
cmd.Parameters.AddWithValue("@BirthPlace", employee.BirthPlace);
cmd.Parameters.AddWithValue("@CurrentPlace", employee.CurrentPlace);
cmd.Parameters.AddWithValue("@Gender", employee.Gender == EmployeeGender.M ? 1 : 0);
cmd.Parameters.AddWithValue("@Department", employee.Department.GetStringValue());
cmd.Parameters.AddWithValue("@OIB", employee.OIB);
ExecuteSqlCommand(cmd);
return cmd.LastInsertedId;
}
void ExecuteSqlCommand(MySqlCommand cmd)
{
try
{
// execute the SQL command
cmd.ExecuteNonQuery();
}
catch (MySqlException e)
{
// log the error
throw new Exception(
String.Format("Error executing the command '{0}'. The error is '{1}'.",
cmd, e.Message));
}
}
为什么有些值在数据库中保存时是 NULL 而有些不是?
【问题讨论】:
-
你检查过 SaveEmployee 方法中的员工对象值了吗?
-
由于某种原因,调试器没有捕捉到对该方法的调用,所以我无法真正检查它。我是 Visual Studio 的新手,所以也许我在调试器上做错了。
-
然后将日志记录添加到保存到员工类的位置,因为这听起来像是值并没有进入该类
-
似乎值并没有进入控制器本身。所以可能你可以在这个方法上设置一个断点并尝试调试。如果您遇到断点问题,请尝试将数据记录到文件或其他内容中,并确保数据正确输入
-
@wesleyy 断点问题仅针对此特定方法?或者断点根本没有命中代码中的任何地方?
标签: c# mysql asp.net asp.net-mvc rest