Home > Net >  EF Core updating multiple entities within one database access or split them up
EF Core updating multiple entities within one database access or split them up

Time:12-09

I have the to decide about the following problem:

2 Objects (i.e. Order and Budget, here simplified):

class Order {
  double Price;
}

class Budget{
   double InternalBudget;
   double ProjectBudget;
}

Now the following question: When a new order is added, the budget has to be updated too. Now, what is the better approach:

Doing both in one dataAccess-method, like:

Order SaveOrderAndUpdateRemainingBudget(Order order, budget updateBudget)
{
  // add/update both to DB and dbContext.SaveChanges()
}

or

Order UpdateOrder(Order order)
{
  // update order
}

Budget UpdateBudget(Budget budget)
{
  // update budget and dbContext.SaveChanges()
}

My thoughts about the second approach: if updating the budget fails, I have an inconsistent DB state, the order is inserted but the budget has an outdated value.

Any suggestions on the best way of handling that?

CodePudding user response:

What I would do is have the UpdateOrder and UpdateBudget methods like you have, but they don't save in those methods. So you would do it like so...

 UpdateOrder(order);
 UpdateBudget(budget);
 dbContext.SaveChanges();

That way the order is encapsulated in its own repository and budget is in another. Then save changes finishes it off.

Your option 2 will create problems like you say.

Each entity should be in charge of itself and know nothing about other entities unless absolutely necessary. Remember that methods should only do one thing in an ideal world, try to approach it with that in mind.

  • Related