Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Let's define a generic repository base class which will allow us to define repository methods that will work with a generic entity type instead of a specific entity type.
Follow Along
To follow along committing your changes to this course, you'll need to fork the dotnet-comic-book-library-manager repo. Then you can clone, commit, and push your changes to your fork like this:
git clone <your-fork>
cd dotnet-comic-book-library-manager
git checkout tags/v3.5 -b creating-a-generic-base-repository-class
Keyboard Shortcuts
-
CTRL+M
CTRL+O
- Collapse to Definitions
Additional Learning
Using a Stub to Delete Entities in a Generic Base Repository Class
In order to keep our approach as simple as possible, we implemented the Delete
method using a retrieve/remove approach:
public void Delete(int id)
{
var set = Context.Set<TEntity>();
var entity = set.Find(id);
set.Remove(entity);
Context.SaveChanges();
}
The downside of this approach is that it requires us to retrieve the entity before we remove it. We can avoid the extra query to retrieve the entity by switching to an entity stub approach. But to do that within our generic BaseRepository class, there are a couple of changes that we need to make to our generic constraints.
public abstract class BaseRepository<TEntity>
where TEntity : class, IEntity, new()
{
...
}
Notice that we added IEntity
and new()
as generic constraints. The IEntity
constraint enforces that the generic type implement the IEntity interface and the new()
constraint enforces that the generic type define a default constructor.
By enforcing that the generic type implement the IEntity interface and have a default constructor, we can instantiate an instance of the generic type and set any of the properties defined on the IEntity interface like this:
public void Delete(int id)
{
var entity = new TEntity()
{
Id = id
};
Context.Entry(entity).State = EntityState.Deleted;
Context.SaveChanges();
}
For reference, here's the IEntity interface:
public interface IEntity
{
int Id { get; set; }
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up