What is the relevance of the Generic Repository Pattern in .Net Core with Entity Framework

c# entity-framework entity-framework-core generic-repository

Question

I am trying (and failing) to understand the purpose of the Generic Repository Pattern in the specific instance where it is wrapped around Entity Framework or EF Core.

what is the benefit of writing this:

public void Update(T obj)
{
    DbContext.Set<T>().Attach(obj);
    DbContext.Entry(obj).State = EntityState.Modified;
    DbContext.SaveChanges();
}

When you get the same and more by simply writing it as

public void Update(Movie obj)
{
    DbContext.Set<Movie>().Attach(obj);
    DbContext.Entry(obj).State = EntityState.Modified;
    DbContext.SaveChanges();
}

or

public void Update(Movie obj)
{
    var movie = DbContext.Movies.FirsOrDefault(x => x.MovieId == obj.MovieId);
    DbContext.Entry(movie).CurrentValues.SetValues(obj);
    DbContext.SaveChanges();
}

I guess my real question is why do we wrap a generic repo around what is basically already a generic repository (with more features and optimisations)?

1
4
3/6/2020 1:21:35 PM

Accepted Answer

Without being too presumptuous, I would like to answer my own question based off of the comment thread.

The generic repository pattern is a hold-over from the days before the era of Object-Relational Mappers (ORM's) like Entity Framework, xHibernate, Dapper, PetaPoco and a million others.

With the advent of the ORM, all the features found in the Repository Pattern are encapsulated within the ORM itself.

For instance, Entity Framework by default uses a Transaction/UnitOfWork each time you call .SaveChanges() on the DbContext.

It also automatically tracks changes made to entities returned by a query unless you explicitly tell it not to with UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).

As far as Generic Repositories are concerned, what do you think the following code is:

MyDbContext.Set<WeatherForecast>().Add(forecast);
0
3/9/2020 8:41:59 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