gpt4 book ai didi

c# - 如何使用 entitystate.modified 更新外键?

转载 作者:行者123 更新时间:2023-11-30 16:59:39 25 4
gpt4 key购买 nike

我是 MVC3 的新手,我试图在编辑内容两个外键(BRANCH_ID、ITEM_MASTER_ID)后执行更新功能。
当 branch_id 或 Item_master_id 未更改时,我面临的问题很容易,行得到更新,但如果外键更改,它会抛出一个错误:

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.

这是我的模型

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; }
}

我的编辑功能代码

[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);
}

帮助我执行更新,即使我的外键被更改。

这是我改进的编辑代码

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);
}

最佳答案

我想你忘记附加对象了:

db.Materials.Attach(material);
db.Entry(material).State = EntityState.Modified;
db.SaveChanges();

关于c# - 如何使用 entitystate.modified 更新外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23490510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com