I am having problem with saving the changes to database.
I am updating the model A in my controller, however when I save the changes using SaveChanges() I end up having a duplicated item in database for B.
After the UpdateModel() is called I inspected the Bs property and it was as I expected however right after the SaveChanges() is called if I inspect the Bs property I will see that the Id is completely different (new Id and new entry).
My class is similar to this:
public class A
{
[HiddenInput(DisplayValue = false)]
public int AId { get; set; }
public string Name { get; set; }
public virtual ICollection<B> Bs{ get; set; }
}
public class B
{
[HiddenInput(DisplayValue = false)]
public int BId { get; set; }
public string Name { get; set; }
public virtual ICollection<A> As{ get; set; }
}
My Controller is like this :
[HttpPost]
public ActionResult Edit(A theA)
{
try
{
db.Entry(theA).State = EntityState.Modified;
foreach (var item in theA.Bs)
{
db.Entry(item).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Am I doing something wrong ?
Thanks in advance