Following statement in EF 6
db.ReceivedMessages.AddOrUpdate(r => r.PatientId == status.PatientId &&
r.DialogId == status.ConversationId, record);
produces exception:
The properties expression 'r => Convert(((r.PatientId == Convert(value(ManagerDB+<>c__DisplayClass6_0).status.PatientId)) AndAlso (r.DialogId == value(ManagerDB+<>c__DisplayClass6_0).status.ConversationId)))' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.
Changed expression to:
db.ReceivedMessages.AddOrUpdate(r => new { r.PatientId, r.DialogId }, record);
Got another exception:
The binary operator Equal is not defined for the types 'System.Nullable`1[System.Guid]' and 'System.Guid'.
How to use AddOrUpdate()
properly to update by 2 columns: if PatientId-DialogId pair exists - update record, if not - insert new one?
Bug should be fixed in EF 6.2.0: https://github.com/aspnet/EntityFramework6/issues/9
Workaround: install EF beta version or insert-update like suggested in above comment:
ReceivedMessage record = db.ReceivedMessages.FirstOrDefault(p => p.PatientId == status.PatientId &&
p.DialogId == status.ConversationId);
// Add new if not exists
bool newRecord = false;
if (record == null)
{
record = new ReceivedMessage();
record.Id = Guid.NewGuid();
newRecord = true;
}
// Save fields
// ...
// Save to DB
if (newRecord) // Workaround for EF 6.1 bug: https://stackoverflow.com/a/44811951/630169
db.ReceivedMessages.Add(record);
else
db.Entry(record).CurrentValues.SetValues(record);
db.SaveChanges();