简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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