What is the correct way to add or update an entity with Entity Framework

c# entity-framework-6

Question

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?

1
1
11/27/2017 11:47:30 AM

Accepted Answer

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).

0
11/27/2017 1:42:41 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow