I’m using EF with CosmosDb, and I’m a bit confused about the change tracking and an error I’m getting when trying to save an entity. So my code looks a bit like this:
ChatUser user = new ChatUser("example");
var response = new ChatMessage()
{
AttachedToEntityId = attachedToEntityId,
CustomerId = user.CustomerId,
FromAiService = true,
FromUser = new ChatUser(isChatBot: true),
ToUser = user,
Content = html
};
dbContext.ChatLog.Add(chatMessage);
await dbContext.SaveChangesAsync(ct);
This gives me a strange error to do with the ‘ToUser’ property and primary key. So I have to change the ToUser assignment to:
ToUser = new ChatUser(user),
(Where I have a constructor that copies all the properties to the new instance).
The error is:
System.InvalidOperationException: ‘Unable to track an entity of type ‘ChatMessage.ToUser#ChatUser’ because its primary key property ‘ChatMessageAttachedToEntityId’ is null.’
I can see it’s related to the change tracking and it not attaching one entity to another, but in reality I just want it to treat the object graph as a whole and save it, not track these properties separately.
Can anyone explain the error, and is there a way to do what I was originally trying to do without needing to cloning the ‘user’ to a new instance? I’ve tried marking ‘ChatUser’ with [ComplexType] but it doesn’t like the ToUser property being nullable if I do that.