gpt4 book ai didi

c# - 更正 EF 6 中 AddOrUpdate() 的多个条件

转载 作者:行者123 更新时间:2023-11-30 17:33:04 25 4
gpt4 key购买 nike

EF 6 中的以下语句

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

产生异常:

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 }'.

将表达式更改为:

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

还有一个异常:

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

如何正确使用 AddOrUpdate() 更新 2 列:如果 PatientId-DialogId 对存在 - 更新记录,如果不存在 - 插入新记录?

最佳答案

错误应在 EF 6.2.0 中修复:https://github.com/aspnet/EntityFramework6/issues/9

解决方法:安装 EF beta version或像上面评论中建议的那样插入更新:

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

关于c# - 更正 EF 6 中 AddOrUpdate() 的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44797167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com