Reputation: 629
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
Upvotes: 1
Views: 3252
Reputation: 1611
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);
Upvotes: 1