我有一个实体(我首先使用代码)看起来像这样:
public class Node
{
public int ID { get; set; }
public string SomeInfo { get; set; }
public virtual Node Previous { get; set; }
public virtual Node Next { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
例如,保存Next Node没有问题.但是,如果Previous的ID为1,并且我尝试将Next Node(ID为1的那个)设置为2,则抛出此异常.
无法将对象添加到对象上下文中.object sEntityKey有一个ObjectStateEntry,指示对象已经参与了不同的关系.
我正在保存这样的节点:
int nextId;
int previousId;
if (int.TryParse(Request["previous"], out previousId))
node.Previous = this.nodeRepository.GetSingle(previousId);
if (int.TryParse(Request["next"], out nextId))
node.Next = this.nodeRepository.GetSingle(nextId);
this.nodeRepository.Update(node);
Run Code Online (Sandbox Code Playgroud)
更新如下所示:
public virtual void Update(T entity)
{
this.context.Entry(GetSingle(entity.ID)).State = EntityState.Detached;
this.context.Entry(entity).State = EntityState.Added;
this.context.Entry(entity).State = EntityState.Modified;
this.Save();
}
Run Code Online (Sandbox Code Playgroud)
和GetSingle这样:
public virtual T GetSingle(object id)
{
var query = this.entities.Find(id);
return query;
}
Run Code Online (Sandbox Code Playgroud)
更新1
具有异常的行在Update方法中:
this.context.Entry(entity).State = EntityState.Modified;
Run Code Online (Sandbox Code Playgroud)
您的上下文是否位于 using 块中并在某个时刻被丢弃?我遇到过类似的“无法将对象添加到对象上下文中。”错误。我会将“上一个”和“下一个”的 Id 添加到模型中,并使用它们来更新外键。
public class Node
{
public int ID { get; set; }
public string SomeInfo { get; set; }
public virtual Node Previous { get; set; }
public int PreviousId { get; set; }
public virtual Node Next { get; set; }
public int NextId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
要更新外键...
int nodeId; // I'm assuming you know the id of node you want updated.
int nextId;
int previousId;
using (var context = new Context())
{
// Perform data access using the context
var node = context.Nodes.find(nodeId);
node.NextId = nextId;
node.PreviousId = previousId;
context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)