1

I'm trying to pull data from a rest endpoint and saving it into a database. However I want to update a record if it already exists, or create it when it doesn't exist yet.

I have the following code:

private void Sync()
{
        using (var db = new context())
        {
            // get data from rest endpoint
            foreach (var item in array)
            {
                // create entity
                var myEntity = new MyEntity();

                // Method 1
                db.Entry(myEntity).State = EntityState.Modified;

                // Method 2
                db.myEntities.AddOrUpdate(e => new { e.att1, e.att2, }, myEntity);
            }

            db.SaveChanges();
        }
    }

Which method would work better for the behaviour I want, if at all?

2
  • 1
    AddOrUpdate() was intended for Seeding, I don't think it is recommended for this kind of general use.
    – H H
    Nov 27, 2017 at 11:41
  • How would you know whether the data already exist?
    – grek40
    Nov 27, 2017 at 11:49

1 Answer 1

2

Try to retrieve the existing entity from the DB using its primary key. If it does not exist, create a new entity. Then map the properties to the retrieved/created entity and save it.

using (var db = new context()) {
    // get data from rest endpoint
    foreach (var item in array) {
        // try to retrieve existing entity
        var myEntity = db.MyEntity.Find(item.Id);

        // if entity does not already exist -> create new
        if (myEntity == null) {
            myEntity = new MyEntity();
            db.MyEntity.Add(myEntity);
        }

        // map received values
        myEntity.Property1 = item.Property1;
        myEntity.Property2 = item.Property2;
    }

    // EntityState should be set automatically by EF ChangeTracker
    db.SaveChanges();
}

Sidenote regarding API design: most of the time it is better to have explicit create and update methods, because these usecases tend to differ. For example: if some values can only be set when creating the entity (e.g. CreationTimestamp, CreatedBy), but not during update, you got a good handle on this if you split the methods. Else you have to resort to sending additional flags in the command (IsUpdateUsecase).

1
  • Ah I see. I was under the false assumption Enity Framework would handle this for me. Thanks for the clarification.
    – Luminai
    Nov 27, 2017 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.