A generic repository for .NET Entity Framework 6 with Async operations

Free Code!

Taking advantage of .NET generics can save you loads of repetitive data access leg work. Since it’s likely that each of your data tables will require the same basic operations (Get, Find, Add, Update, Delete) you’d be better off writing these functions once instead of recreating them for each data model (DRY).

Generics are classes, interfaces, or methods that have placeholder values for the data type parameter it uses rather than specifying it implicitly. When you create an instance of a generic class, you specify what type of data you intend to use with the class and the placeholder is substituted for that class.

For example, a simple generic class with a single generic parameter would look like:

T is the generic placeholder in this case. When you instantiate this class, you’ll specify what type T is, and every T placeholder in the class will be replaced with that type during the classes lifespan.

Entity Framework can benefit from generic classes frequently because there are so many common operations that can be performed regardless of the data type being acted upon. In a recent post I talked about the benefits of using Async data calls for your MVC + EF6 application. The following is a generic repository for Entity Framework 6 with methods for both synchronous and asynchronous data operations. When you create an instance of your repository service, simply inherit from this Base Repository and pass in the data type of your object and you’ll gain all of these capabilities out of the gate for the service.

If you need to provide specific functionality on a specific data type, just override the method and you’re good to go. For more usage information or to contribute / improve upon this class, visit the GitHub project.

Insider: How the basic tech behind the Internet works
Join the discussion
Be the first to comment on this article. Our Commenting Policies