繁体   English   中英

ArangoDb.Net upsert总是插入

[英]ArangoDb.Net upsert always insert

我正在使用ArangoDatabase及其驱动程序制作带有CRUD功能的小型应用程序:

http://www.arangoclient.net/

这是我的代码:

        var insert = new Account
        {
            Email = "email01@gmail.com",
            FirstName = "Adam",
            LastName = "Smith"
        };

        var update = new Account
        {
            Email = "email01@gmail.com",
            FirstName = "John",
            LastName = "Peterson"
        };

        using (var arangoDatabase = new ArangoDatabase(new DatabaseSharedSetting()
        {
            Url = "http://127.0.0.1:8529/",
            Database = "_system",
            Credential = new NetworkCredential()
            {
                UserName = "root",
                Password = "xvxvc"
            }
        }))
        {
            arangoDatabase.Query()
                .Upsert(_ => new Account() {Email = insert.Email},
                    _ => insert, ((aql, x) => update))
                    .In<Account>()
                    .Execute();
        }

首次运行时,[插入]对象被添加到数据库中。 因此,我的数据库现在是:

数据已成功导入

但是在第二次运行代码时,它引发了一个错误:

unique constraint violated (while executing). ErrorNumber: 1210 HttpStatusCode: 409

问题是:我的问题是什么以及如何解决?

谢谢,

在此处输入图片说明

问题可能是向上搜索表达式序列化:

假设Account类定义为:

public class Account
{
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

更新搜索表达式: new Account() {Email = insert.Email}将序列化为:

{ Email: "email01@gmail.com", FirstName: null, LastName: null }

但预期的是:

{ Email: "email01@gmail.com" }

由于搜索表达式将永远找不到文档,因此将发生插入操作,并且unique constraint violated

有两种解决方案可以避免序列化FirstNameLastName成员:

一种是我们可以使用Json.net JsonProperty属性忽略序列化中的空值:

public class Account
{
    public string Email { get; set; }
    [Newtonsoft.Json.JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string FirstName { get; set; }
    [Newtonsoft.Json.JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string LastName { get; set; }
}

另一种方法是将匿名对象用于搜索表达式:

arangoDatabase.Query()
                .Upsert(_ => new Account() {Email = insert.Email}

// should be

arangoDatabase.Query()
                .Upsert(_ => new {Email = insert.Email}

关于使用匿名对象的一个​​注意事项是, Email成员可以根据您为其命名约定指定的内容来解析其他内容,例如:

public class Account
{
    [DocumentProperty(Identifier = IdentifierType.Key)]
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

如果将Email指定为密钥标识符, _key在匿名对象中使用_key

arangoDatabase.Query() .Upsert(_ => new { _key = insert.Email }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM