2017-07-07 20 views
0

我正在尝试将JSON对象发布到我的服务,反序列化并将其保存到数据库。它的工作 - 种。问题是JSON的某些字段被保存到数据库中,而其他字段则为空。向MySQL数据库发布空值的服务

例如,发布此JSON时:

{ 
"FirstName": "Michael", 
"LastName": "Ledley", 
"BirthPlace": "Austria", 
"Gender": "M", 
"OIB": "12348879991", 
"CurrentPlace": "New Guinea", 
"Department": "D_21570" 
} 

...在数据库中只有CurrentPlaceGenderDepartment存储正确的,而所有其他值(FirstNameLastNameBirthPlace,... )是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,有些不是时候保存在数据库中?

+1

您是否在SaveEmployee方法中检查了员工对象值? –

+0

由于某种原因,调试器不能捕获对该方法的调用,所以我无法真正检查它。我是新来的视觉工作室,所以也许我做错了调试器。 – wesleyy

+0

然后将日志记录添加到员工类的保存位置,因为它听起来像值不会进入该类 – BugFinder

回答

0

您可能会发现将您的Parameter对象更完全地填充很有用。

而不是...

MySqlCommand cmd = new MySqlCommand(sqlString, conn); 
cmd.Parameters.AddWithValue("@FirstName", employee.FirstName); 
    ... 

试试这个。

MySqlCommand cmd = new MySqlCommand(sqlString, conn); 
cmd.Parameters.Add("@CategoryName", SqlDbType.VarChar, 45).Value = employee.FirstName; 
    ... 

重点是明确声明参数的数据类型和长度。

相关问题