Developer Guide
Upserting Records

    The Upsert operation inserts or edits one or more Entity records depending on the status of the record. To determine whether a record already exists, the upsert statement uses the record's ID as the key to match records. Developers can alternatively use a different field to be used for matching. For example, when upserting a list of Contact records, the Email field may be used as the key to match records and determine whether the record exists or not.

    • If the key is not matched, a new record is created.
    • If the key is matched once, the existing record is updated.
    • If the key is matched multiple times, an error is generated and the record is neither inserted or updated.
     

    See below for an example of upserting Contacts:

    Contact c1 = Database.Query<Contact>().Where(a=>a.Email == "jsmith@testman.com").First();
    Contact c2 = new Contact { Firstname="Sam", Lastname="Davidson", Email="sdavidson@mailorg.com" };
    List<Contact> cons = newList<Contact> { c1, c2 };
    
    try
    {
       Upsert(cons);
    }
    catch(DatabaseException ex)
    {
        //handle errors here
    }
    

     

    Below follows an example of upserting for another field (other than ID):

    Contact c = new Contact { Firstname="John", Lastname="Smith", Email="jsmith@testman.com" };
    
    try
    {
       Upsert(c, new { ExternalIdField="Email" });
    }
    catch(DatabaseException ex)
    {
        //handle errors here
    }

     

    Processing in System Mode

    ​The Magentrix for Database operation validates the user's access and verifies that user has the "create" or "update" permission as necessary. However, in some scenarios, the database operation should take place regardless of the user's premission. In such cases use the SystemMode flag.

    Upsert(contacts, new { SystemMode=true });

     

    Transactional Commit

    If you want all records to be commited together or rolled back in case of an error, set the AllOrNone flag to true. This flag by default is false.

    Upsert(contacts, new { AllOrNone=true });

    See Database options for more detail.