简体   繁体   中英

Value cannot be null. Entity

I have web API

I try to send request from postman

Here is my Model

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace trackingappbackend.Models
{
    using System;
    using System.Collections.Generic;

    public partial class StartWorkingDay
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public int Id { get; set; }
        public string Company { get; set; }
        public string Date { get; set; }
        public string Time { get; set; }
        public string INN { get; set; }
    }
}

And here is controller

// POST: api/StartWorkingDays
    [ResponseType(typeof(StartWorkingDay))]
    public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.StartWorkingDays.Add(startWorkingDay);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
    }

I pass data like on screen

在此处输入图片说明

But I have this error

Value cannot be null. Parameter name: entity

How I can fix it?

You are sending the data in the request body and your Post method doesn't know that. You can change your Post method to add [FromBody] to extract the data from the body.

[ResponseType(typeof(StartWorkingDay))]
public IHttpActionResult PostStartWorkingDay([FromBody]StartWorkingDay startWorkingDay)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.StartWorkingDays.Add(startWorkingDay);
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
}

also, try to debug your method to see if your startWorkingDay parameter is deserialized with the data sent.

Hope that helpes.

Omar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM