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 function in an API Controller that accepts a complicated object as an argument. This complicated object contains a list of objects of the class "BudgetDetail" and an object of type "Budget" (the database's master table) (that are the details of the master class).

I have to add the "Budget" class object to the master table, followed by the "BudgetDetail" class list in the details table.

The API Controller's HttpPost function looks like this:

[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 problem I'm having is that the BudgetId value from the master database is null when I attempt to put it into the "BudgetDetails" table. How do I enter data into the Budget table as the master and get the Budget table's ID to insert into the Details table? (BudgetDetails).

The class included in the argument is as follows:

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

My budget class (Master table) looks like this:

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

My BudgetDetail class (Detail table) looks like this:

 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 extremely appreciative of any advice you may provide me.

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

Popular Answer

ZZZ_tmp
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