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

c# entity-framework-6

Question

In order to save data into a database, I'm attempting to get it from a rest endpoint. But if a record already exists, I want to update it, and if not, I want to create it.

I own the next 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 approach, if any, would be more effective for the desired behaviour?

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

Accepted Answer

ZZZ_tmp
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