简体   繁体   English

在 EF Core 中添加或更新实体

[英]Add or update entity in EF Core

I have an entity with a recursive relationship like:我有一个具有递归关系的实体,例如:

public class Message {
   [Key]
   public int MessageId { get; set; }

   public int? ReplyToMessageId { get; set; }

   public Message ReplyToMessage { get; set; }

   public ICollection<Message> ReplyMessages { get; set; }
}

JSON data: { "messages": [ { "id": 1, "reply_to": null, "replied_messages": [ { "id": 2, "reply_to": 1, "replied_messages": [] }, { "id": 3, "reply_to": 1, "replied_messages": [] } ] } ] } JSON 数据: { "messages": [ { "id": 1, "reply_to": null, "replied_messages": [ { "id": 2, "reply_to": 1, "replied_messages": [] }, { "id": 3, "reply_to": 1, "replied_messages": [] } ] } ] }

I create an instance of the message(id 1) and replied messages(id 2,3,4) from JSON data and add the replies(id 2,3,4) to message(id 1) as ReplyMessages, also, the message(id 1) already exist in the database我从 JSON 数据创建消息(id 1)和回复消息(id 2,3,4)的实例,并将回复(id 2,3,4)添加到消息(id 1)作为回复消息,还有消息(id 1) 已存在于数据库中

I need to have an add or update method to save the messages So i write following code:我需要一个添加或更新方法来保存消息所以我写了以下代码:

public void AddOrUpdate(Message message) {
  if(Context.Messages.Any(m => m.MessageId == message.MessageId))
    Context.Messages.Update(message);
  else
    Context.Messages.Add(message);
    Context.SaveChanges();
}

This method make an exception when I pass an existing message with a collection of new replied messages当我传递带有新回复消息集合的现有消息时,此方法会产生异常

Database operation expected to affect 1 row(s) but actually affected 0 row(s).数据库操作预计会影响 1 行,但实际上会影响 0 行。 Data may have been modified or deleted since entities were loaded.自加载实体以来,数据可能已被修改或删除。

I test BulkMerge method of the Entity Framework Extensions library and it's work fine but I'm looking for a solution with ef core without any extension我测试了Entity Framework Extensions库的BulkMerge方法,它工作正常,但我正在寻找一个没有任何扩展的带有 ef 核心的解决方案

More Information:更多信息:

Database Provider: Postgresql
EF Core Version: 5.0.2

It seems like ef core tracking issue.这似乎是 ef 核心跟踪问题。 If you add AsNoTracking() to query locally or globally, commenting may solve the issue.如果添加AsNoTracking()进行本地或全局query ,评论可能会解决问题。

Also without changing tracking behaviour you can try something like this:此外,在不改变跟踪行为的情况下,您可以尝试以下操作:

context.Entry(Message).CurrentValues.SetValues(changed_message_model);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM