Fix several conditions for AddOrUpdate () in EF 6

The next statement in EF 6

db.ReceivedMessages.AddOrUpdate(r => r.PatientId == status.PatientId && 
                                    r.DialogId == status.ConversationId, record);

      

throws an exception:

Property Expression 'r => Convert (((r.PatientId == Conversion (value (ManagerDB + <> c__DisplayClass6_0) .status.PatientId)) AndAlso (r.DialogId == value (ManagerDB + <> c__DisplayClass6_0) .status.ConversationId ))) It does not work. The expression must represent a property: C #: 't => t.MyProperty' VB.Net: 'Function (t) t.MyProperty'. When specified, 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:

 db.ReceivedMessages.AddOrUpdate(r => new { r.PatientId, r.DialogId }, record);

      

There is one more exception:

Binary operator Equal is not defined for types 'System.Nullable`1 [System.Guid]' and 'System.Guid'.

How to use it correctly AddOrUpdate()

for updating by 2 columns: if there is a PatientId-DialogId pair - update the record, if not - insert a new one?

+3


source to share


1 answer


Bug in EF 6.2.0: https://github.com/aspnet/EntityFramework6/issues/9

Workaround: Install EF Beta or Paste-Update as shown in the comment above:



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();

      

+1


source







All Articles