EF Core pass TEntity for dbContext to do Update or Add

Viewed 143

Using EF Core, I have 10 methods that basically do the same thing. Update or Add and then SaveChanges()

i.e.

  public void UpdateUser(User model)
    {
        if(... some condition.. to determine to add or update)
        {
            db.Update(model);
            db.Entry(model).State = EntityState.Modified;
        }
        else
        {        
           db.User.Add(model);
        } 
        db.SaveChanges(); 
    }

  public void UpdateCompany(Company model)
       {
        if(... some condition.. to determine to add or update)
        {
            db.Update(model);
            db.Entry(model).State = EntityState.Modified;
        }
        else
        {        
           db.Company.Add(model);
        } 
        db.SaveChanges(); 
    }

possible to create one method and just pass Entity want to update or add?

2 Answers

the real difference between Update and Add is PrimaryKey values. when u try to Update a data which is contains null PrimaryKey its not gonna update the data , its gonna add that data. u can controll the model to learn is it update or not . if PrimaryKey is null it can add that data. if the PrimaryKey is not null u can Update the data :

    public void UpdateOrAdd(Company model)
    {
        if(model.CompanyID !=0) //The primary key
        {
            db.Update(model);
            db.Entry(model).State = EntityState.Modified;
        }
        else
        {        
           db.Company.Add(model);
        } 
        db.SaveChanges(); 
    }

EF creates a PrimaryKey value after the db.SaveChanges(); method.

i suggest u to put try catch on that db.SaveChanges(); method as a last thing. u can get the error message and show it to yourself with a SweetAlert, u can give a correct message is that action %100 success or not.

You can use a generic method. If you need access to the DbSet for an entity use db.Set<TEntity>() instead of the declared DbSet properties, db.Users or db.Comanies.

    public void Update<TEntity>(TEntity entity) where TEntity: class
    {

        if (1==1 /*whatever*/)
        {
            db.Update(entity);
        }
        else
        {
            db.Set<TEntity>().Add(entity);
        }
        db.SaveChanges();
    }
Related