This workshop will be retired on May 1, 2025.
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 see how to update our approach for deleting comic books to handle concurrency.
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 that utilizes a stub entity approach in the ComicBooksRepository class instead of the BaseRepository generic base class. To implement this method in the generic base class, we need to add a couple of generic constraints.
public abstract class BaseRepository<TEntity>
where TEntity : class, IVersionedEntity, new()
{
...
}
Notice that we added IVersionedEntity
and new()
as generic constraints. The IVersionedEntity
constraint enforces that the generic type implement the IVersionedEntity interface and the new()
constraint enforces that the generic type define a default constructor.
By enforcing that the generic type implement the IVersionedEntity interface and have a default constructor, we can instantiate an instance of the generic type and set any of the properties defined on the IVersionedEntity interface like this:
public void Delete(int id, byte[] rowVersion)
{
var entity = new TEntity()
{
Id = id,
RowVersion = rowVersion
};
Context.Entry(entity).State = EntityState.Deleted;
Context.SaveChanges();
}
For reference, here's the IVersionedEntity interface:
public interface IVersionedEntity
{
int Id { get; set; }
byte[] RowVersion { 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