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:
POST api/Suppliers/. POST api/SupplierProduct.So my questions are:
Actually, it depends on your use-case. If your API is totally faced publicly, i would advice using DTO's. If it is for yourselve or for an internal team, i would stick with OData EF Models ( because it is quicker)
You can ( as usual) give the entire entity through your api.
You can use a viewmodel ( more like DTO's when using it in an API, but it's the same thing) and transform the methods accordingly. You can use automapper for that - it also transforms the $filter query, an example is found here : Web API Queryable - how to apply AutoMapper?.
Don't forget, an API has a lot of awesome advantages. OData uses Batch and Patch to change your entities. So i personally stick with Odata as entites most of the time, but that's a personal choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With