简体   繁体   中英

Is it a bad practice to create extension methods for DbSet<T>?

I'm sort of new to EF Core and was wondering if creating extension methods for DbSet was a misuse of it.

I have many long queries in my codebase that I think would benefit (maintainability speaking) from being extension methods.

To me, this

 var appUsersSegments = dbContext.ApplicationUsersSegments
    .Where(a => a.App.AppId == selectedApp.AppId)
    .OrderBy(a => a.CreatedDate)
    .ToList();

Could easily be

 var appId = 232;
 var appUsersSegments = dbContext.ApplicationUsersSegments.FindRecent(appId);

As this would prevent my code from being bloated with the same long query here and there.

Is there something I don't know about DbSet or EF Core that would be better than creating extension methods?

You should probably not since it will be harder to maintain in the long run.

It also enables the developers to write bad code.

For example, directly calling the DbContext from anywhere with an extension method while saying it's code reuse without any abstraction.

The best practice would be to implement a service, whether using a repository pattern or even CQRS pattern , that abstracts the usage of the DbContext and just have this piece of code in there instead of an extension.

Then later for reusability you can call the service to execute your code rather than the extension.

This will give you control over your dependencies in these snippets and you will be able to switch implementations with dependency injection in an easier way.

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