我在这里查找了类似的问题“对象引用没有设置为对象的实例。”我很肯定我存储在数据库中的信息是相同的类型,但显然有些东西是关闭的。
我的目标是将两个参数传递给“PUT”请求(ID和食物对象)
以下是实体制作的食物对象:
public partial class Food
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Food()
{
this.MealFoods = new HashSet<MealFood>();
}
public int FoodID { get; set; }
public string FoodName { get; set; }
public int Calories { get; set; }
public string Notes { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<MealFood> MealFoods { get; set; }
}
在下面的代码中:
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
FoodID = Convert.ToInt32(Request.QueryString["ID"]),
FoodName = editFoodNameString.ToString(),
Calories = Convert.ToInt32(EditCalories.Text.Trim()),
Notes = EditNotes.Text.Trim()
});
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:63591/");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.PutAsJsonAsync("api/foods/" + Request.QueryString["ID"], json);
您可以看到我正在序列化一个对象以将其发送到后端。一旦我将它发送到后端,就会转到这里:
private MySwoleMateEntities db = new MySwoleMateEntities();
[ResponseType(typeof(void))]
public IHttpActionResult PutFood(int id, [FromBody] string foodJson)
{
Food food = new Food();
food = JsonConvert.DeserializeAnonymousType(foodJson, food);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Entry(food).State = EntityState.Modified;
try
{
db.SaveChanges(); //Where the error happens
}
catch (DbUpdateConcurrencyException)
{
if (!FoodExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
我创建了一个Food对象的新实例,因为那是我将在数据库中编辑的对象。然后我创建一个匿名对象,并将JSON字符串“foodJson”设置为数据库中的Food对象类型。
我检查了食物对象,它显示所有值都在正确的空格中,而且它们的类型正确。
任何建议?