C# 仅当EntityKey属性的当前值为null时,才能设置该属性
我正试图以以下方式执行EF更新,但仍收到此错误: 仅当EntityKey属性的当前值为null时,才能设置该属性C# 仅当EntityKey属性的当前值为null时,才能设置该属性,c#,entity-framework-4,C#,Entity Framework 4,我正试图以以下方式执行EF更新,但仍收到此错误: 仅当EntityKey属性的当前值为null时,才能设置该属性 如果您能了解我如何解决此问题并执行上述语句,我将不胜感激 在此场景中不要使用AddObject。它用于插入新实体,但您正在更新现有实体。改为使用附加: using (hydraEntities db = new hydraEntities()) { db.youusers.Attach(YouUser); db.ObjectStateManager.ChangeObj
如果您能了解我如何解决此问题并执行上述语句,我将不胜感激 在此场景中不要使用
AddObject
。它用于插入新实体,但您正在更新现有实体。改为使用附加:
using (hydraEntities db = new hydraEntities())
{
db.youusers.Attach(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}
在我的场景中,我通过不同的线程一次添加了好几次对象。执行此操作时,我必须锁定模型容器对象,以确保一次只处理一个对象
using (hydraEntities db = new hydraEntities())
{
db.youusers.Attach(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}