Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 202
Azzaronn Avatar asked Dec 03 '19 09:12

Azzaronn


People also ask

What is better way to update data in EF core?

Update Data With Entry() Method In EF core Because you're creating a new instance (which isn't tracked) instead of updating the existing instance (which is tracked).

Is the repository pattern dead?

That is, it's dead if you are using Entity Framework Core. If you're still using straight ADO.NET, or even just dapper, then the repository pattern still probably makes sense for you.

Is the repository pattern useful with Entity Framework Core?

No, the repository/unit-of-work pattern (shortened to Rep/UoW) isn't useful with EF Core. EF Core already implements a Rep/UoW pattern, so layering another Rep/UoW pattern on top of EF Core isn't helpful.


1 Answers

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

like image 102
DNakevski Avatar answered Nov 15 '22 06:11

DNakevski