Reputation: 685
I using Odata Webapi with EF6 and my models are as below
public class Company
{
Public Company()
{
Products = new List<Product>();
}
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public List<Product> Products { get; set; }
}
public class Product
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
I need to expose an end point to add product/s to an existing Company. the end point has to be something like below.
Post: ~odata/Company(1)/Products with body as List of products json.
body:[{"Name":"Product1"},{"Name":"Product2"}]
Upvotes: 0
Views: 381
Reputation: 239
I would suggest using an bound ODataAction for this purpose. You would need to pass in a DTO containing a list of Products.
An example for DTO would be:
public class CreateProductsDTO
{
List<Product> Products { get; set; }
}
Then you would need to register an bound action to Company controller:
var action = builder.EntityType<Company>().Action("AddProducts");
action.Parameter<CreateProductsDTO>("Value");
In the controller you need to define an action like:
[HttpPost]
public async Task<IHttpActionResult> AddProducts([FromODataUri] Guid key, ODataActionParameters parameters)
{
//read parameter from ODataActionParameters
var createProducts = parameters["Value"] as CreateProductsDTO;
//Process information
}
The request for this would look like this:
Post: ~odata/Company(1)/AddProducts
body:
{ "Value" : {
"Products" :
[{"Name":"Product1"},{"Name":"Product2"}]
}
}
Hope this helps. Regards, Mihai
Upvotes: 1