Repository Pattern EF Core Update method

asp.net-core-mvc c# entity-framework-core

Question

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.

1
6
12/3/2019 9:10:13 AM

Accepted Answer

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

0
12/3/2019 10:25:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow