Insert records into tables with master/detail relationship with Entity Framework and MVC

asp.net-mvc asp.net-web-api c# entity-framework-6

Question

I have a HttpPost method into an API Controller that it takes as a parameter a complex object. This complex object has an object of the type of the class 'Budget' (that is the master table in the Database), and it has a List of 'BudgetDetail'class (that are the details of the master class).

I need to insert the object of 'Budget' class in the master table, and then insert the list of the 'BudgetDetail' class in the details table

This is the HttpPost method of the API Controller:

[HttpPost]
public IHttpActionResult CreateBudget(NewBudget newBudget)
{
    var budget = new Budget
    {
        DateOfIssue = newBudget.Budget.DateOfIssue,
        VehicleId = newBudget.Budget.VehicleId,
        BudgetAccepted = newBudget.Budget.BudgetAccepted 
    };

    _context.Budgets.Add(budget);

    foreach (var detail in newBudget.BudgetDetails)
    {
        var detailBudget = new BudgetDetail
        {
            //BudgetId = Here i need to get id of the Budget table that i inserted before
            ProductId = detail.ProductId,
            Price = detail.Price,
            Quantity = detail.Quantity,
            Iva = detail.Iva,
            Total = detail.Total
        };
        _context.BudgetDetails.Add(detailBudget);
    }
    _context.SaveChanges();
    return Ok();
}

The issue that i have here is that when i try to insert into the 'BudgetDetails' table the value of BudgetId of master table is null. How can i insert in the master table (Budget) and get the id of that table (BudgetId) to insert in the details table (BudgetDetails).

This is the class that is in the parameter:

public class NewBudget
{
    public Budget Budget{ get; set; }
    public List<BudgetDetail> BudgetDetails{ get; set; }
}

This is my Budget class (Master table):

public class Budget
{
    public int Id { get; set; }
    public DateTime DateOfIssue { get; set; }
    public int VehicleId { get; set; }
    public bool BudgetAccepted { get; set; }
}

This is my BudgetDetail class (Detail table):

 public class BudgetDetail
{
    public int Id { get; set; }
    public int BudgetId { get; set; }
    public int ProductId { get; set; }
    public byte Quantity { get; set; }
    public int Price { get; set; }
    public int Iva { get; set; }
    public int Total { get; set; }
}

I will be very grateful for any suggestions you give me.

1
0
8/16/2017 12:52:57 AM

Popular Answer

In CreateBudget method, change the end. Something like:

context.BudgetDetails.Add(detailBudget);
}
_context.SaveChanges();
return detailBudget.Id;

It gives you the created detailBudget id from EF.

1
8/16/2017 1:06:24 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow