简体   繁体   中英

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": [] } ] } ] }

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

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). 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

More Information:

Database Provider: Postgresql
EF Core Version: 5.0.2

It seems like ef core tracking issue. If you add AsNoTracking() to query locally or globally, commenting may solve the issue.

Also without changing tracking behaviour you can try something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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