Add Or Update EF Core7

150 views Asked by At

What is the most efficient way to implement add or update using Entity Framework Core 7 for IEnumerable<MyEntity> myentities?

Tried to loop through each item and

myDBContext.CustomAddUpdate(item);
myDBContext.SaveChanges();

CustomAddUpdate method use entry for given entity and get the state Add or Update of DBContext.

1

There are 1 answers

1
Lucky On BEST ANSWER

Hello I think I understand what you want to do, please see if the following works for you:

public void AddOrUpdateRange(IEnumerable<MyEntity> myentities)
    {        
        var listForAddEntities= new List<MyEntity>();
        var listForUpdateEntities= new List<MyEntity>();

        foreach (MyEntity entity in myentities)
        {
            var entry = Entry(entity);
            switch (entry.State)
            {
                case EntityState.Detached:
                case EntityState.Added:
                    listForAddEntities.Add(entity);
                    break;
                case EntityState.Modified:
                    listForUpdateEntities.Add(entity);
                    break;
                //For Unchanged nothing to do

                default:
                    //anything you want to do
            }
        }
        AddRange(listForAddEntities);
        UpdateRange(listForUpdateEntities);
    }