简体   繁体   中英

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

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)?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM