Correct multiple condition for AddOrUpdate() in EF 6

.net c# entity-framework-6 insert-update


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?

6/28/2017 6:37:44 PM

Accepted Answer

Bug should be fixed in EF 6.2.0:

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:

6/29/2017 1:17:39 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow