Entity Manager - Updating the reference Id of my model
-
20-06-2021 - |
Question
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
?
Solution 2
Without much talk, here's the code that does the job:
[HttpPost]
public ActionResult EditTablo(Tablo tablo, int? RessamId, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (tablo is TuvalBaski)
{
container.Urun.Attach((TuvalBaski)tablo);
}
else if (tablo is YagliBoya)
{
container.Urun.Attach((YagliBoya)tablo);
}
if (RessamId == null)
{
if(tablo.Ressam != null)
{
container.Ressam.Detach(tablo.Ressam);
}
tablo.Ressam = null;
}
else
{
if (tablo.Ressam != null)
{
container.Ressam.Detach(tablo.Ressam);
}
tablo.Ressam = (from table in container.Ressam
where table.RessamId == RessamId
select table).Single();
container.Ressam.Attach(tablo.Ressam);
}
TryUpdateModel(tablo);
container.SaveChanges();
}
return View(tablo);
}
OTHER TIPS
You have to attach the tablo
instance to the context.
[HttpPost]
public ActionResult EditTablo(Tablo tablo, int? RessamId, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
container.Tablo.Attach(tablo);
container.ObjectStateManager
.ChangeObjectState(tablo, System.Data.EntityState.Modified);
if (RessamId != null)
{
tablo.Ressam = (from table in container.Ressam
where table.RessamId == RessamId
select table).Single();
TryUpdateModel(tablo.Ressam);
}
container.SaveChanges();
}
return View(tablo);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow