I have a generic repository as like that
public class Repository<T> : IRepository<T> where T: class
{
DataContext _db;
public Repository()
{
_db = new DataContext("connection string");
}
System.Data.Linq.Table<T> GetTable
{
get { return _db.GetTable<T>(); }
}
public T GetBy(Func<T, bool> exp)
{
return GetTable.SingleOrDefault(exp);
}
....
}
Is it possible to add a generic method to this repository to check for the existence of any entity like that:
public bool IsExisted(T entity)
{
...
}
it is easy to write it in any repository
_productRepository.GetBy(p => p.Id == 5 // or whatever);
where the productRepository like this:
public class ProductRepository : Repository<Product>
{
public ProductRepository()
: base()
{
}
}
I came to this since i always want to check for the existence of an entity alot, so i don’t need to write the same method in all repositories.
If all your entities have for example a property Guid Id you can create the following interface for your entities:
And restrict your Repository class to it:
You can then define the following function in your base repository: