0

I have looked up similar questions on here about "Object reference not set to an instance of an object.", I am positive that the information I am storing in the database is the same type but clearly something is off.

My objective is to pass in two parameters to a "PUT" request (ID and Food Object)

Here is the food object made by entity:

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; }
}

In the code below:

 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);

You can see that I am serializing a object to send it to the backend. Once I send it to the backend it goes here:

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);
    }

I create a new instance of Food object, since that is the object I will be editing in the database. I then create an anonymous object and set the JSON string of "foodJson" to the Food object types in the database.

I checked the food object and it shows all the values are in the correct spaces and I they are of the correct type.

Any Suggestions?

0 Answers0