Create a record and add relationship through httpPost of Web Api

2

When creating a new record in the tab I need to get the id of my main screen and send it along with the new object. Currently I have this code:

    public async Task<IHttpActionResult> PostMenuProduct(MenuProduct MenuProduct)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.MenuProducts.Add(MenuProduct);
        await db.SaveChangesAsync();

        if (MenuProduct.MenuIdAux != null)
        {
            RelationshipMenuProductWithMenu relationship = new RelationshipMenuProductWithMenu
            {
                MenuProductId = MenuProduct.Id,
                MenuId = Convert.ToInt32(MenuProduct.MenuIdAux)
            };

            await AddRelationshipMenuProductWithMenu(relationship);
        }

        return CreatedAtRoute("DefaultApi", new { id = MenuProduct.Id }, MenuProduct);
    }

In this case I add MenuIdAux to the model to send the Id of my main screen along with the new object. How could I create this relationship without having to add this parameter in my MenuProduct model? I tried to pass as parameter in the post but HttpPost would not accept.

    
asked by anonymous 06.06.2014 / 18:28

1 answer

1

Two ways:

1. Creating a ViewModel identical to your Model, with one more parameter

public class MenuProductViewMode {
    public int MenuIdAux { get; set; }

    // Coloque aqui os outros parâmetros do Model
}

Mount the Model within the method:

public async Task<IHttpActionResult> PostMenuProduct(MenuProductViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var menuProduct = new MenuProduct();
    // Faça todas as atribuições de viewModel para o seu Model aqui

    db.MenuProducts.Add(MenuProduct);
    await db.SaveChangesAsync();

    ...
}

2. Passing as Action Parameter

This way is not as good as the first because the variable is free, but it works.

Put the following as an argument:

public async Task<IHttpActionResult> PostMenuProduct(MenuProduct MenuProduct, int MenuIdAux) { ... }

Put in your sending JSON a field called MenuIdAux that will be done automatically.

    
06.06.2014 / 19:11