Ive been working with MVC for a while now and am used to creating a View Model class for every MVC view. Now I am trying out Web API and I think I may be hung up on this MVC mentality. My relationship looks like this:
public class Supplier
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<SupplierProduct> SupplierProducts { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<SupplierProduct> SupplierProducts { get; set; }
}
public class SupplierProduct
{
public int Id { get; set; }
public string Title { get; set; }
public int SupplierId { get; set; }
public virtual Supplier Supplier { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}
I am working on the creation of the supplier where in the create form the user is able to select multiple products that already exist. In MVC, I would POST a view model that looks something like this:
public class SupplierCreateViewModel
{
public string Title { get; set; }
public ICollection<ProductViewModel> SelectedProducts { get; set; }
}
And in the controller I would first create the new Supplier then create a new SupplierProduct for each SelectedProduct. I implemented something like this in Web API in the POST action of my Supplier oData controller but it doesnt feel right. I think that instead, I need to change my approach and do something like this from the client:
- Scrap the View Model design. (There arent really 'views' anymore anyway)
- Have both a Supplier and a SupplierProduct Controller with a POST action on both.
- On save, send my Supplier create request to
POST api/Suppliers/
. - Using the Id of the Supplier JSON in the response, send multiple create requests to
POST api/SupplierProduct
.
So my questions are:
- Am I heading in the right direction with this approach?
- Instead of View Models is there a different pattern I should use? DTO?
- With the example given, am I forced to send 1 - n requests like that? This feels wrong.