1

I have a db with two tables Invoices and Customers. Customers PK is FK in the Invoices table. I have a Create view in which user fills in invoice data. On this form I have a @Html.DropDownList with SelectList populated with the names of already existing in the db customers. On the basis of user selection customer data fields are autopopulated with customer data from the database via partial view:

@using (Ajax.BeginForm("CustomerSelect", "Invoice", new AjaxOptions{
            HttpMethod = "GET",
            InsertionMode = InsertionMode.Replace,
            UpdateTargetId = "CustomerFields"}))

This works well, but when I create the Submit button, it creates a new instance of the cutomer in the database, even though it should use the id of one retrieved from the db. When the partial view is displayed on the Create view it displayes proper Customer ID:

<div class="editor-label">
    @Html.LabelFor(model => model.Customer)

    <div class="editor-field">
        @Html.EditorFor(model => model.Customer)
        @Html.ValidationMessageFor(model => model.Customer)
    </div>
</div>

But when I look inside the invoice object in the httppost of controler Create method it shows shows a different (new) Customer ID:

[HttpPost]
public ActionResult Create(Invoice invoice)
{
    if (ModelState.IsValid)
    {
        db.Invoices.Add(invoice); **//invoice.Customer.CustomerID == 1**
        db.SaveChanges(); **//invoice.Customer.CustomerID changes to next free in the db == 7**
        return RedirectToAction("Index");
    }

   return View(invoice);
}

What am I doing wrong?

tereško
  • 58,060
  • 25
  • 98
  • 150
Eric
  • 11
  • 3

1 Answers1

3

The Add method adds all entities in the entity graph. So if your invoice instance has Customer property set and you call Add it creates new records for both customer and invoice.

If you want to add only invoice you have few options:

  • Expose CustomerID on invoice and don't work with navigation property. That will offer you foreign key association which is much easier to use in this scenario.
  • Change the state of the customer instance back to unchanged so that only invoice and relation between invoice and customer are considered as added.

Example:

db.Invoices.Add(invoice); 
db.Entry(invoice.Customer).State = EntityState.Unchanged;
db.SaveChanges(); 
Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670