Reputation: 8926
I am using two POCO classes:
public class GearModel
{
public long Id { get; set; }
public Int16 LocationNumber { get; set; }
public string HooksPerRod { get; set; }
public string TerminalWeightBait { get; set; }
public string TerminalWeight { get; set; }
public FlyModel Shrimps { get; set; }
public FlyModel Worms { get; set; }
public FlyModel Cocahoes { get; set; }
public FlyModel Scampi { get; set; }
}
public class FlyModel
{
public double? Number { get; set; }
public string Color { get; set; }
}
When I try to posts to my API Controller (defined below), it Complains Null value for non-nullable member. Member: 'Worms'.
, when using this cURL command to post to it (I know none of the cURL parameters are the issue, if I include all the FlyModel
properties it works).
Not Working
curl -X POST -v -H "Content-Type: application/json" --data-ascii "{Assn:102,LocationNumber:1,HooksPerRod:3,TerminalWeightBait:'None',TerminalWeight:'18oz',Shrimps:{Number:0.0,Color:'Pink'}}" <Url Here>
Working
curl -X POST -v -H "Content-Type: application/json" --data-ascii "{Assn:102,LocationNumber:1,HooksPerRod:3,TerminalWeightBait:'None',TerminalWeight:'18oz',Shrimps:{Number:0.0,Color:'Pink'},Worms:{},Cocahoes:{},Scampi:{}}" <Url Here>
So my question is, how do I allow the FlyModel properties (Shrimps, Worms, etc) to be completely left out of the JSON like in the not working cURL command?
GearController
public class GearController : ApiController
{
// POST: api/Gear
[ResponseType(typeof(GearModel))]
public async Task<IHttpActionResult> PostGearModel(GearModel gearModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Gear.Add(gearModel);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = gearModel.Assn }, gearModel);
}
}
Upvotes: 2
Views: 98
Reputation: 3924
I assume you are referring to the error after db.SaveChangesAsync();
which is by Entity Framework
, Web Api
does not change anything here. The error happens because EF
does not allow complex types nullability, that means you need to instantiate every complex type Shrimps, Worms...
before saving.
You can read more about this convention at: Complex Types of Nullable Values or Complex Types Nullability Convention
Upvotes: 1