I'm developing an Asp.Net MVC Application and trying to make a generic method to check if a specific record exists in DB or not by using passed entityId to this method. Something like below:
public bool CheckIfUserExistsByUserId(int userId)
{
return _userRepository.DbSet().Any(u => u.Id == userId);
}
But this method only checks _userRepository and accepts an integer as entityId.
My problem is where I want to put this generic method as a general method in my BaseService just like other general methods that I write below:
public class BaseService<TModel> : IBaseService<TModel> where TModel : class
{
private readonly IUnitOfWork _unitOfWork;
private readonly IBaseRepository<TModel> _baseRepository;
public BaseService(IUnitOfWork unitOfWork, IBaseRepository<TModel> baseRepository)
{
_unitOfWork = unitOfWork;
_baseRepository = baseRepository;
}
public BaseService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public void Add(TModel entity)
{
this._baseRepository.Add(entity);
}
public void Remove(TModel entity)
{
this._baseRepository.Remove(entity);
}
/// <summary>
/// Remove All Provided Items At Once .
/// </summary>
/// <param name="itemsToRemove"></param>
public void RemoveRange(IEnumerable<TModel> itemsToRemove)
{
_baseRepository.RemoveRange(itemsToRemove);
}
public TModel FindById<T>(T key)
{
return _baseRepository.FindById(key);
}
public void Commite()
{
this._unitOfWork.Commite();
}
}
But in this case, I can't get the primary key field of the entity that passed to my method from Entity Framework. Also, I don't want to pass the primary key field of the entity to my method in everywhere I use the mentioned method. Is it possible to getting the primary key field of the entity in EF?
Edit: According to request of the other users I added my IBaseRepository source code here:
public interface IBaseRepository<TModel> where TModel : class
{
/// <summary>
/// Add New Entity .
/// </summary>
/// <param name="entity"></param>
void Add(TModel entity);
/// <summary>
/// Remove Item From Database .
/// </summary>
/// <param name="entity"></param>
void Remove(TModel entity);
/// <summary>
/// Remove All Provided Items At Once .
/// </summary>
/// <param name="itemsToRemove"></param>
void RemoveRange(IEnumerable<TModel> itemsToRemove);
/// <summary>
/// Get The Underlying Type's DbSet .
/// </summary>
/// <returns></returns>
DbSet<TModel> DbSet();
/// <summary>
/// Find Item By Id .
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
TModel FindById<T>(T key);
}