gpt4 book ai didi

entity-framework - Entity Framework 链表

转载 作者:行者123 更新时间:2023-12-03 17:57:06 26 4
gpt4 key购买 nike

我有一个看起来像这样的实体(我首先使用代码):

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

例如保存下一个节点没有问题。但是,如果上一个的 ID 为 1 并且我尝试将下一个节点(即 ID=1 的节点)设置为 2,则会引发此异常。

The object cannot be added to the object context. The object�s EntityKey has an ObjectStateEntry that indicates that the object is already participating in a different relationship.



我正在像这样保存节点:
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);

更新看起来像这样:
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();
}

和 GetSingle 像这样:
public virtual T GetSingle(object id)
{
var query = this.entities.Find(id);
return query;
}

更新 1

有异常(exception)的行在 Update 方法中:
this.context.Entry(entity).State = EntityState.Modified;

最佳答案

您的上下文是否在 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; }
}

要更新外键...
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();
}

关于entity-framework - Entity Framework 链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9813808/

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