简体   繁体   English

父实体上的WebAPI POST子级

[英]WebAPI POST Child on Parent Entity

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. 我有一个WebAPI项目,其中包含两个控制器:带有GET,POST,PUT和DELETE的ProductController。 and CategoryController with GET that includes Products, POST, PUT and DELETE. 以及带有GET的CategoryController,其中包括Products,POST,PUT和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. 我尝试使用对父类别的引用来调用ProductController的POST方法,但它会在数据库中创建一个新类别。

Do i have to use the PUT method of Category ? 我必须使用类别的PUT方法吗?

Regards. 问候。

Try changing up your models a little bit. 尝试稍微修改一下模型。

Add a CategoryId to your product entity as a foreign key. 将CategoryId作为外键添加到您的产品实体。 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. 现在,当您发布到产品控制器时,请确保将CategoryId随其传递。 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. 但是,鉴于您提供的信息,这才是我真正能想到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM