I have a Tablo object, which has a reference to a Ressam object. In my Edit action for Tablo, I want to be able to change the Ressam reference too, i.e referencing another RessamId. Here’s the controller code, let’s say I only want to change the Ressam of the Tablo in my call:
[HttpPost]
public ActionResult EditTablo(Tablo tablo, int? RessamId, HttpPostedFileBase image)
{
// Here, I successfully get RessamId, no problem there
if (ModelState.IsValid)
{
// this is where I attach the Tablo object
if (tablo is TuvalBaski)
{
container.Urun.Attach((TuvalBaski)tablo);
}
else if (tablo is YagliBoya)
{
container.Urun.Attach((YagliBoya)tablo);
}
// and this is the part where I change the Ressam reference
if (RessamId == null)
{
tablo.Ressam = null;
container.Ressam.Attach(tablo.Ressam);
TryUpdateModel(tablo.Ressam);
}
else
{
tablo.Ressam = (from table in container.Ressam
where table.RessamId == RessamId
select table).Single();
//container.Ressam.Context.ObjectStateManager.ChangeObjectState(tablo.Ressam, System.Data.EntityState.Modified);
//container.ObjectStateManager.ChangeObjectState(tablo.Ressam, System.Data.EntityState.Modified);
container.Ressam.Attach(tablo.Ressam);
TryUpdateModel(tablo.Ressam);
}
return View(tablo);
}
By the way, this doesn’t work. How can I update the reference id in my Tablo entity, so that it can show another Ressam?
Without much talk, here’s the code that does the job: