Azzaronn
Azzaronn

Reputation: 167

Repository Pattern EF Core Update method

I have a question about using the Repository Pattern and Unit of Work pattern in a MVC Web Application with Entity Framework Core.

I am currently implementing the update functionality in the controller. Now, at this point I am not sure what the best way is to update the entity. I have watched some videos where they said that an Update method should not be present in a repository like this:

public T Update(T entity)
{
  DbSet.Attach(entity);
  var entry = Context.Entry(entity);
  entry.State = System.Data.EntityState.Modified;
}

So that means that I will have to do it like this in the controller:

public IActionResult Edit(int id, [Bind("NeighbourhoodGroup,Neighbourhood,NeighbourhoodId")] Neighbourhoods neighbourhoods)
{
  var neighbourhoodsFound = unitOfWork.Neighbourhoods.Get(id);
  neighbourhoodsFound.Neighbourhood = neighbourhoods.Neighbourhood;
  neighbourhoodsFound.NeighbourhoodGroup = neighbourhoods.NeighbourhoodGroup;
}

However, that means that I will have to do this in all controllers, even if the object has alot of Properties?

I hope someone can give me some advice on what the best approach would be.

Upvotes: 11

Views: 13456

Answers (2)

DNakevski
DNakevski

Reputation: 310

In your repository you can have the update functionality as simple as this:

public void Update(T entity)
    {
        DbSet.Attach(entity);
        ApplicationContext.Entry(entity).State = EntityState.Modified;
    }

While in the controller or from wherever you prefer to do your update you can get the entity preferably by id, modify all the properties that you want to modify on entity, call the the Update method from the repository which is going to set its state to modified and finally call the Save or SaveAsync method on the EF context. Your EF context should be exposed in your UnitOfWork.

For more detailed explanation you can see this post, it will be very helpful. EF Repository Pattern

Upvotes: 4

Maxim Tkachenko
Maxim Tkachenko

Reputation: 5808

  1. I don't see the problem in having Update method in repository. It's OK. It's more complex to read data from repository based on criteria. here you can check an example from Microsoft.
  2. Controller isn't a good place to describe your business cases: do some business logic then save to repository etc. Consider MediatR as a way to describe particular business case instead of putting it into controller.

Also it's useful to read about clean architecture.

Upvotes: 0

Related Questions