0

My current solution is as follows - I want to know whether this is correct.

Inside a HttpPost action method, I have the following code - Case type is an entity, case variable is passed as a parameter into the action method:

Case caseInRepository = _unitOfWork.CaseRepository.FindById(case.Id);

caseInRepository.UpdateState(case);

_unitOfWork.CaseRepository.Update(caseInRepository);
_unitOfWork.CaseRepository.SaveChanges();

The UpdateState method maps the fields of the argument (which are the edited fields) to the instance. Some fields are ignored, since they were not set in the view, and are null.

My question is, with Entity Framework, the

_unitOfWork.CaseRepository.Update(caseInRepository);

line is not necessary, since entities are tracked. However, I am not sure if it is right to remove it, since not all data storage support change tracking. I am also not sure if it is right to call FindById to get the item from the datastore.

1 Answer 1

0

I think your questions arise from the architecture you propose. One big concern about your solution is encapsulation: who does what?

The repository pattern should abstract the data access layer to the consumer. So the consumer is essentially telling the interface: I want you to update this entity in the database, how you do that is none of my business.

But in your implementation you assume that the object returned by FindById is EF tracked and therefore can track changes in your MVC controller. This is a leaky abstraction.

If we don't follow this logic, FindById will return an entity that is not tracked by EF. The entity will be updated in the MVC controller and then the repository's Update function will update the latest version in the DB.

How do you do that? Well, in most cases you don't track domain entities in EF, you create a special database DTO used for that purpose (here and here for more details).

However, if you don't want to do that, the repository pattern is not the only architecture that can be used to solve these kinds of problems. Try looking at the Vertical Slice Architecture.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.