Max Stanley Max Stanley - 3 months ago 10
ASP.NET (C#) Question

One-To-Many Relationship not editing Child table

public class Class1
{
public Guid Class1ID { get; set; }
public string class1string { get; set; }
public virtual Class2 Class2 { get; set; }
}

public class Class2
{
public Guid Class2ID { get; set; }
public string class2string { get; set; }
}

// POST: Class1/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Guid id, [Bind("Class1ID,Class2,class1string")] Class1 class1)
{
if (id != class1.Class1ID)
{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
_context.Update(class1);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!Class1Exists(class1.Class1ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(class1);
}


Instead of the Edit changing the data that is in the child table, it creates an new row in the table and changes the GUID in the parent table. The Parent table is edited correctly.

Any help will be greatly appreciated.

Answer

I have also been struggling with this problem.

When I make an edit and save it I hit the function public async Task Edit(Guid id,[Bind("Class1ID,Class2,class1string")] Class1 class1) (as you would expect) -

All the values are correct except class1.Class2.Class2ID which is an empty guid {00000000-0000-0000-0000-000000000000}

As a result when SaveChangesAsync is called EF creates a new record for Class2, rather than updating the existing record as intended.

The is because the binding is failing, it can't find the value for Class2.Class2ID.

This is because the Get is failing to load this value as it is almost certainly not on the page.

Add the following line to your view markup (suggest next to input type="hidden" asp-for="Class1ID")

 <input type="hidden" asp-for="Class2.Class2ID" />

This should enable the binding to work.

I hope this helps.