Reputation: 79
I have the following models :
public class Product
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public Category Category { get; set; }
}
public class Category
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
I have a WebAPI project that contains two controllers : ProductController with GET, POST, PUT and DELETE. and CategoryController with GET that includes Products, POST, PUT and DELETE.
I want to be able to add a product in an existing category, but i don't know how to perform that.
I've tried to call the POST method of my ProductController with the reference to a parent category but it create a new category in my database.
Do i have to use the PUT method of Category ?
Regards.
Upvotes: 1
Views: 1134
Reputation: 56
Try changing up your models a little bit.
Add a CategoryId to your product entity as a foreign key. If each product has one category, but a category can have many products that makes it a 1-to-many relationship.
Now when you post to the product controller, make sure to pass the CategoryId with it. That establishes a relationship between the two and you'll be able to select information about the category via a join or however you want to approach the problem.
I'm assuming your using Entity Framework for your Data access? But given the information you gave, that's all I can really come up with.
Upvotes: 2