The trick is to put a where
type restriction for your generic type on your BaseRepository
class. Try something similar to this:
WARNING: air code ;-)
Base model:
public interface IDbTable
{
bool IsActive { get; set; }
}
public class DbTable
{
public bool IsActive { get; set; }
}
Your model
public class Category : DbTable
{
public int CatId { get; set; }
public string CatName { get; set; }
}
public class Product : DbTable
{
public int PrdId { get; set; }
public string PrdName { get; set; }
}
Your repository
public interface IBaseRepository<T> where T : class, IDbTable
{
void Deactivate<T>(T entity);
}
public class BaseRepository<T> : IBaseRepository
{
public void Deactivate<T>(T entity)
{
entity.IsActive = false;
}
}
You could go even further and extend your IDbTable to include even more generic and helpful columns. E.g.
public interface IDbTable
{
int Id { get; set; }
bool IsActive { get; set; }
DateTime UpdatedOn { get; set; }
DateTime CreatedOn { get; set; }
}
Repo
public interface IBaseRepository<T> where T : class, IDbTable
{
T GetById(int id);
void Add(T entity);
void Update(T entity);
void Deactivate(T entity);
}
public class BaseRepository<T> : IBaseReposiotry<T>
{
public T GetById(int id)
{
//code to get the entity by id
}
public void Add(T entity)
{
entity.CreatedOn = DateTime.UtcNow;
entity.UpdatedOn = DateTime.UtcNow;
}
public void Update(T entity)
{
entity.UpdatedOn = DateTime.UtcNow;
}
public void Deactivate(T entity)
{
entity.IsActive = false;
}
}
These two articles should help you out as well:
new Repository().DoMagic()
Implementing a Simple Generic Repository with LinqToSql
HTHs,
Charles