I’m using EF Core with CosmosDb, and I’m a bit confused about the change tracking and an error I’m getting when trying to save an entity.
My code looks 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 causes a strange error about the ToUser
property and primary key. 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.