I think you forgot to attach the object:
db.Materials.Attach(material);
db.Entry(material).State = EntityState.Modified;
db.SaveChanges();
سؤال
I am new to MVC3 im trying to perform update function after edit which contents two foreign keys (BRANCH_ID,ITEM_MASTER_ID).
The problem im facing easy when branch_id or Item_master_id are not changed the row gets updated but if the foreigns keys change its throwing me an error:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
Here is my model
public partial class MATERIAL
{
public int ID { get; set; }
public int ITEM_MASTER_ID { get; set; }
public int BRANCH_MASTER_ID { get; set; }
public string NAME { get; set; }
public string ADDRESS_DETAILS { get; set; }
public virtual BRANCH_MASTER BRANCH_MASTER { get; set; }
public virtual ITEM_MASTER ITEM_MASTER { get; set; }
}
My edit function code
[HttpPost]
public ActionResult Edit(MATERIAL material)
{
if (ModelState.IsValid)
{
db.Entry(material).State = EntityState.Modified;
db.SaveChanges();
int tempid = material.ID;
return RedirectToAction("listcontinue", new { id = tempid });
}
return View(material);
}
Help me in perform update even if my foreigns keys are changed.
here is my improved edit code
public ActionResult Edit(MATERIAL material)
{
var temp = Convert.ToString(material.ITEM_NAME);
using (var context = new material_managementEntities())
{
var temp1 = (from cs in context.ITEM_MASTER
where cs.ITEM_NAME == temp
select cs.ID).FirstOrDefault();
material.ITEM_MASTER_ID = temp1;
}
var temp2 = Convert.ToString(material.ITEMGROUP);
using (var context = new material_managementEntities())
{
var temp3 = (from cs in context.ITEM_GROUP_MASTER
where cs.ITEM_GROUP_NAME == temp2
select cs.ID).FirstOrDefault();
material.ITEM_MASTER_ITEM_GROUP_MASTER_ID = temp3;
}
if (ModelState.IsValid)
{
db.MATERIALs.Attach(material);
db.Entry(material).State = EntityState.Modified;
db.SaveChanges();
int tempid = material.ID;
return RedirectToAction("listcontinue", new { id = tempid });
}
return View(material);
}
المحلول
I think you forgot to attach the object:
db.Materials.Attach(material);
db.Entry(material).State = EntityState.Modified;
db.SaveChanges();
نصائح أخرى
I think in the context EF doesn't know about the foreign keys, I had to use an includes first before I update the foreign key:
db.Entry(team).State = EntityState.Modified;
db.SaveChanges();
var updatedTeam = db.Teams.Include(x=> x.GameType).Where(x=> x.ID == team.ID).Single();
updatedTeam.GameType = db.GameTypes.Find(GameTypeId);
db.SaveChanges();